﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.ComponentModel;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;
using System.Transactions;
using WebServiceSmart.Router;
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Route;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using log4net;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using WebServiceSmart.Model;
using MySql.Data.MySqlClient;

namespace WebServiceSmart
{
    public partial class MyService
    {
        public static string QGZHIFUQGAPPID = ConfigurationManager.AppSettings["QGZHIFUQGAPPID"];
        public static string QGZHIFUCHSK = ConfigurationManager.AppSettings["QGZHIFUCHSK"];
        public static string QGZHIFUCHAPPID = ConfigurationManager.AppSettings["QGZHIFUCHAPPID"];
        public static string QGZHIFUACCOUNTNUMBER = ConfigurationManager.AppSettings["QGZHIFUACCOUNTNUMBER"];

        public static string BIAOQGZHIFUCOMPANY = "qgzhifucompanybiao";
        public static string BIAOQGZHIFURECORD = "qgzhifurecordbiao";
        public static string BIAOALLYOUHUIQUAN = "qgzhifualluseryouhuiquan";
        public static string BIAOCOMYOUHUIQUAN = "qgzhifuallcomyouhuiquan";
        public static string BIAOALLFINANCE = "qgzhifualluserfinance";


        public static string S_SHOP = "s_shop";
        public static string S_ORDER = "s_order";


        public static string QGZSAPPID = ConfigurationManager.AppSettings["zhifuwecahrtappid"];
        public static string QGZSSECRET = ConfigurationManager.AppSettings["zhifuwecahrtsecret"];
        public static string XCXBACKURL = ConfigurationManager.AppSettings["zhifubackurl"];
        public static string RefundBackurl = ConfigurationManager.AppSettings["refundbackurl"];
        public double QGFEILV = 0.003;//青贯平台金额的费率
        public double QGMINSHOUXU = 0.01;//青贯平台金额的费率母





        private static string GetCompanyDDNumber(mysqlcli mainsql, string comdate, string companyaccount)
        {
            string nowdate = DateTime.Now.ToString("yyyyMMdd");

            int Goodscount = 1;
            string oldid = "";
            string olddate = "";
            oldid = comdate;
            try
            {
                olddate = oldid.Substring(0, 8);
            }
            catch
            {

            }
            if (nowdate == olddate)
            {
                string countstr = oldid.Remove(0, 8);
                int.TryParse(countstr, out Goodscount);
                Goodscount++;
            }
            else
            {
                Goodscount = 1;
            }
            string command = string.Format("update {0} set com_numberdate='{1}' WHERE com_account='{2}' ",
                BIAOQGZHIFUCOMPANY, nowdate + Goodscount.ToString(), companyaccount);
            mainsql.SqlExcuteNoReturn(command);


            return Goodscount.ToString("D4");
        }

        //查支付表的信息
        private static bool CheckZhiFuComBiao(mysqlcli mainsql, string companyaccount, ref Dictionary<string, string> mapargs)
        {


            //获取青贯配置参数
            string sqlcmd = string.Format("SELECT * from {0} where com_account='qingguan' AND com_number='00000' ;", BIAOQGZHIFUCOMPANY);
            DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            mapargs.Add("qgfeilv", ds.Rows[0]["com_comfeilv"].ToString());
            mapargs.Add("qgminshouxu", ds.Rows[0]["com_minshouxu"].ToString());
            mapargs.Add("qgamount", ds.Rows[0]["com_amount"].ToString());
            //获取交易公司配置参数
            sqlcmd = string.Format("SELECT * from {0} where com_account='{1}' AND com_status='授权' ;", BIAOQGZHIFUCOMPANY, companyaccount);
            ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            mapargs.Add("com_numberdate", ds.Rows[0]["com_numberdate"].ToString());
            mapargs.Add("com_comfeilv", ds.Rows[0]["com_comfeilv"].ToString());
            mapargs.Add("com_minshouxu", ds.Rows[0]["com_minshouxu"].ToString());
            mapargs.Add("com_lingqianfeilv", ds.Rows[0]["com_lingqianfeilv"].ToString());
            mapargs.Add("com_lingqianminshouxu", ds.Rows[0]["com_lingqianminshouxu"].ToString());
            mapargs.Add("com_jinbibeilv", ds.Rows[0]["com_jinbibeilv"].ToString());
            mapargs.Add("com_jinbimincz", ds.Rows[0]["com_jinbimincz"].ToString());
            mapargs.Add("com_name", ds.Rows[0]["com_name"].ToString());
            mapargs.Add("com_number", ds.Rows[0]["com_number"].ToString());
            mapargs.Add("com_amount", ds.Rows[0]["com_amount"].ToString());
            mapargs.Add("com_daishouztfeilv", ds.Rows[0]["com_daishouztfeilv"].ToString());
            mapargs.Add("com_daishouminshouxu", ds.Rows[0]["com_daishouminshouxu"].ToString());
            mapargs.Add("com_daishouztopen", ds.Rows[0]["com_daishouztopen"].ToString());
            ds.Dispose();
            return true;
        }

        //查商户订单的信息
        private static bool CheckZhiFuSHDDBiao(mysqlcli mainsql, string order_id, ref Dictionary<string, string> mapargs)
        {
            string sqlcmd = string.Format("SELECT * from {0} where order_id='{1}';", S_ORDER, order_id);
            DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            var userid = ds.Rows[0]["order_to_user_id"].ToString();
            mapargs.Add("shop_id", ds.Rows[0]["shop_id"].ToString());
            mapargs.Add("order_pay_time", ds.Rows[0]["order_pay_time"].ToString());
            mapargs.Add("order_pay_liushui", ds.Rows[0]["order_pay_liushui"].ToString());
            mapargs.Add("order_price", ds.Rows[0]["order_price"].ToString());
            mapargs.Add("order_to_user_id", userid);
            //获取青贯配置参数
            sqlcmd = string.Format("SELECT t1.*,t2.c_account from {0} t1 left join {2} t2 on t1.shop_id=t2.shop_id where t1.shop_id='{1}' AND shop_status='0' ;", S_SHOP, mapargs["shop_id"], BIAOCH);
            ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }

            var shoprate = ds.Rows[0]["shop_rate"]?.ToString();
            if (string.IsNullOrWhiteSpace(shoprate))
            {
                shoprate = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
            }
            //查询有没有特殊推广分成
            var shopmodel = mainsql.SqlExcuteWithReturn($"select tg_yongjin,tg_tag,tg_rate from {BIAOUSER} t2 left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id"
                + " where t2.user_onlyid='" + userid + "'").ToModels().FirstOrDefault();
            //查询店铺能不能适用特殊推广分成
            if (!string.IsNullOrWhiteSpace(shopmodel["tg_tag"]))
            {
                var tags = ds.Rows[0]["shop_ation"]?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                //店铺标签匹配上特殊推广标签
                if (tags != null && tags.Length > 0 && tags.Contains(shopmodel["tg_tag"]))
                {
                    //特殊费率
                    if (!string.IsNullOrWhiteSpace(shopmodel["tg_yongjin"]))
                        shoprate = shopmodel["tg_yongjin"];
                }
            }
            mapargs.Add("ch_account", ds.Rows[0]["c_account"]?.ToString());
            mapargs.Add("shop_rate", shoprate);
            mapargs.Add("shop_balance", ds.Rows[0]["shop_balance"].ToString());
            mapargs.Add("shop_lock_balance", ds.Rows[0]["shop_lock_balance"].ToString());
            mapargs.Add("shop_name", ds.Rows[0]["shop_name"].ToString());
            sqlcmd = string.Format("SELECT * from {0} where com_account='qingguan' AND com_number='00000' ;", BIAOQGZHIFUCOMPANY);
            ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            mapargs.Add("qgnumber", ds.Rows[0]["com_number"].ToString());
            mapargs.Add("qgnumberdate", ds.Rows[0]["com_numberdate"].ToString());

            sqlcmd = string.Format("SELECT * from {0} where user_onlyid='{1}' ;", BIAOYONGHUUSER, mapargs["order_to_user_id"]);
            ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }

            mapargs.Add("user_phone", ds.Rows[0]["user_phone"].ToString());
            mapargs.Add("user_name", ds.Rows[0]["user_name"].ToString());

            ds.Dispose();
            return true;
        }
        //查商户ID的信息
        private static bool CheckZhiFuSHIDBiao(mysqlcli mainsql, string shop_id, ref Dictionary<string, string> mapargs)
        {

            //获取青贯配置参数
            string sqlcmd = string.Format("SELECT * from {0} where shop_id='{1}' AND shop_status='0' ;", S_SHOP, shop_id);
            DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            var shoprate = ds.Rows[0]["shop_rate"]?.ToString();
            if (string.IsNullOrWhiteSpace(shoprate))
            {
                shoprate = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
            }
            mapargs.Add("shop_rate", shoprate);
            mapargs.Add("shop_name", ds.Rows[0]["shop_name"].ToString());
            mapargs.Add("shop_balance", ds.Rows[0]["shop_balance"].ToString());

            sqlcmd = string.Format("SELECT * from {0} where com_account='qingguan' AND com_number='00000' ;", BIAOQGZHIFUCOMPANY);
            ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                return false;
            }
            mapargs.Add("qgnumber", ds.Rows[0]["com_number"].ToString());
            mapargs.Add("qgnumberdate", ds.Rows[0]["com_numberdate"].ToString());

            ds.Dispose();
            return true;
        }


        //查用户的财务表信息
        private static bool CheckUserFinBiao(mysqlcli mainsql, string companyaccount, string useronlyid)
        {


            //获取青贯配置参数
            string sqlcmd = string.Format("SELECT * from {0} where fin_useronlyid='{1}' AND fin_companyaccount='{2}' ;", BIAOALLFINANCE, useronlyid, companyaccount);
            DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            if (ds.Rows.Count == 0)
            {
                sqlcmd = string.Format("INSERT INTO {0} (fin_useronlyid,fin_companyaccount,fin_lingqian,fin_jinbi,fin_jifen)" +
                   " VALUES ('{1}','{2}','0','0','0')",
                  BIAOALLFINANCE, useronlyid, companyaccount);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);

            }


            ds.Dispose();
            return true;
        }

        //查用户的财务表信息
        private static string GetYHQID()
        {
            string yhqid = "YHQ" + Guid.NewGuid().ToString();
            return yhqid;
        }


        private static string CheckYhqReturnCost(DataRow yhqrow, ref Dictionary<string, string> mapargs)
        {
            string biaocost = mapargs["biaocost"];
            string retcost = "";
            if (yhqrow["yhq_status"].ToString() != "未使用")
            {
                mapargs["ErrorMsg"] = "优惠券已经被使用";
                return "";
            }
            if (yhqrow["yhq_chugangaccount"].ToString() != "")
            {
                if (yhqrow["yhq_chugangaccount"].ToString() != mapargs["biaochuaccount"])
                {
                    mapargs["ErrorMsg"] = "您必须使用优惠券规定出港的运单";
                    return "";
                }
            }
            if (yhqrow["yhq_daogangaccount"].ToString() != "")
            {
                if (yhqrow["yhq_daogangaccount"].ToString() != mapargs["biaodaoaccount"])
                {
                    mapargs["ErrorMsg"] = "您必须使用优惠券规定到港的运单";
                    return "";
                }
            }
            if (yhqrow["yhq_type"].ToString() == "1")//如果为折扣券
            {
                double costdb = 0;
                double.TryParse(biaocost, out costdb);
                double zhekou = 0;
                double.TryParse(yhqrow["yhq_zhekou"].ToString(), out zhekou);
                costdb = costdb * zhekou / 10;
                costdb = Math.Round(costdb, 2);//将手续费变成两位小数
                retcost = costdb.ToString("0.00");
            }
            else if (yhqrow["yhq_type"].ToString() == "2")//如果为满减券
            {
                double costdb = 0;
                double.TryParse(biaocost, out costdb);

                double manjianman = 0;
                double manjianjian = 0;
                double.TryParse(yhqrow["yhq_manjianman"].ToString(), out manjianman);
                double.TryParse(yhqrow["yhq_manjianjian"].ToString(), out manjianjian);

                if (costdb < manjianman)
                {
                    mapargs["ErrorMsg"] = "消费金额不满足满减条件";
                    return "";
                }

                costdb = costdb - manjianjian;
                if (costdb < 0)
                {
                    costdb = 0;
                }
                costdb = Math.Round(costdb, 2);//将手续费变成两位小数
                retcost = costdb.ToString("0.00");
            }
            else
            {
                mapargs["ErrorMsg"] = "获取优惠券失败";
                return "";
            }
            return retcost;
        }

        //传化支付接口通用
        private bool CH_ZHIFU_COMMON(ref Dictionary<string, string> mapargs)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string companyname = mapargs["companyname"];
                string subjectstring = mapargs["subjectstring"];
                string logip = mapargs["logip"];
                string qgliushuinumber = mapargs["qgliushuinumber"];
                string jine = mapargs["jine"];
                string openid = mapargs["openid"];

                string chappid = QGZHIFUCHAPPID;
                string sk = QGZHIFUCHSK;
                string com_accountnumber = QGZHIFUACCOUNTNUMBER;

                String service_id = "tf56pay.gateway.multiPay";
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                paramMap.Add("appid", chappid);
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                paramMap.Add("service_id", service_id);
                paramMap.Add("sign_type", "RSA");
                paramMap.Add("terminal", "PC");
                paramMap.Add("backurl", XCXBACKURL);
                paramMap.Add("fronturl", "http://www.q5688.com");
                paramMap.Add("subject", subjectstring);
                paramMap.Add("businesstype", "商家消费");
                paramMap.Add("kind", "商业服务消费");
                paramMap.Add("description", "测试支付");
                paramMap.Add("businessnumber", qgliushuinumber);
                if (mapargs.ContainsKey("billsubtype"))
                {
                    paramMap.Add("billsubtype", mapargs["billsubtype"]);
                    //paramMap.Add("shareinfo", mapargs["shareinfo"]);//不能传
                    paramMap.Add("billamount", jine);
                }
                else
                {
                    paramMap.Add("transactionamount", jine);
                }
                paramMap.Add("toaccountnumber", com_accountnumber);
                paramMap.Add("bankcode", "WXXCX");
                paramMap.Add("clientip", logip);
                paramMap.Add("merchtonline", "0");
                paramMap.Add("wxappid", QGZSAPPID);
                paramMap.Add("wxopenid", openid);
                string tf_sign = signForm(paramMap, sk);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string jsonStr = JsonConvert.SerializeObject(paramMap);
                string retsult = PostWebRequestForm(baseurl, paramMap);
                logJieKou.Info("聚合支付-" + companyname + "-传化接口返回-" + retsult);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;

                string coderel = retsultJson["code"].ToString();
                string biz_code = retsultJson["biz_code"].ToString();
                string biz_msg = retsultJson["msg"]?.ToString();
                string alldata = retsultJson["data"]?.ToString();
                if (coderel.Equals("GP_00") && biz_code.Equals("GPBIZ_00"))
                {
                    JObject alldataJson = JsonConvert.DeserializeObject(alldata) as JObject;
                    string htmldata = alldataJson["htmldata"].ToString();
                    mapargs.Add("chbusinessrecordnumber", alldataJson["businessrecordnumber"].ToString());
                    htmldata = System.Web.HttpUtility.UrlDecode(htmldata);
                    byte[] bytes = Convert.FromBase64String(htmldata);
                    htmldata = Encoding.GetEncoding("utf-8").GetString(bytes);
                    JObject htmldataalldata = JsonConvert.DeserializeObject(htmldata) as JObject;
                    mapargs.Add("appId", htmldataalldata["appId"].ToString());
                    mapargs.Add("timeStamp", htmldataalldata["timeStamp"].ToString());
                    mapargs.Add("nonceStr", htmldataalldata["nonceStr"].ToString());
                    mapargs.Add("package", htmldataalldata["package"].ToString());
                    mapargs.Add("signType", htmldataalldata["signType"].ToString());
                    mapargs.Add("paySign", htmldataalldata["paySign"].ToString());
                    logJieKou.Info("聚合支付结束-" + companyname + "-Base64htmldata-" + htmldata);
                }
                else
                {
                    mapargs["ErrorMsg"] = "聚合支付返回错误信息" + biz_msg;  //参数错误
                    return false;
                }
            }
            catch (Exception ex)
            {
                mapargs["ErrorMsg"] = ex.Message;  //参数错误
                return false;
            }
            return true;

        }


        //传化支付后置分账接口
        private bool CH_ZHIFU_Share(ref Dictionary<string, string> mapargs)
        {
            try
            {
                ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
                string qgliushuinumber = mapargs["qgliushuinumber"];

                //string qgppid = QGZHIFUQGAPPID;
                string chappid = QGZHIFUCHAPPID;
                string sk = QGZHIFUCHSK;
                string com_accountnumber = QGZHIFUACCOUNTNUMBER;

                String service_id = "tf56pay.gateway.delayedShareConfirm";
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                paramMap.Add("appid", chappid);
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                paramMap.Add("service_id", service_id);
                paramMap.Add("sign_type", "RSA");
                paramMap.Add("terminal", "PC");

                paramMap.Add("backurl", XCXBACKURL);
                paramMap.Add("businessnumber", qgliushuinumber);
                paramMap.Add("shareinfo", mapargs["shareinfo"]);
                paramMap.Add("merchtdevicename", "MAC");

                string tf_sign = signForm(paramMap, sk);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string jsonStr = JsonConvert.SerializeObject(paramMap);
                string retsult = PostWebRequestForm(baseurl, paramMap);

                logJieKou.Info("后置分账-传化接口返回-" + retsult);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                string coderel = retsultJson["code"].ToString();
                string biz_code = retsultJson["biz_code"].ToString();
                string biz_msg = retsultJson["biz_msg"].ToString();
                //string alldata = retsultJson["data"].ToString();
                if (coderel.Equals("GP_00") && biz_code.Equals("GPBIZ_00") || ("GP_00".Equals(coderel) && "GPBIZ_000997".Equals(biz_code)))
                {
                    //JObject alldataJson = JsonConvert.DeserializeObject(alldata) as JObject;
                    //mapargs.Add("chbusinessrecordnumber", alldataJson["businessrecordnumber"].ToString());
                    logJieKou.Info("聚合支付结束-");
                }
                else
                {
                    mapargs["ErrorMsg"] = "聚合支付返回错误信息" + biz_msg;  //参数错误
                    return false;
                }
            }
            catch (Exception ex)
            {
                mapargs["ErrorMsg"] = ex.Message;  //参数错误
                return false;
            }
            return true;

        }


        #region 企业小程序相关


        //企业小程序进入验证
        [WebMethod(Description = "正式版本")]
        public string xcx_companylogin(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();

            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string phone = comrcv.Map_Args["phone"];


                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("SELECT * from {0} where com_account='{1}'  ;", BIAOQGZHIFUCOMPANY, companyaccount);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                if (ds.Rows.Count == 0)
                {
                    ret.Map_Args["ErrorMsg"] = "该公司未开通相关服务";                                    //参数错误
                    goto EXIT;
                }

                if (ds.Rows[0]["com_adminphone"].ToString().IndexOf(phone) == -1)
                {
                    ret.Map_Args["ErrorMsg"] = "您不能进入公司后台系统";                                    //参数错误
                    goto EXIT;
                }
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序进入验证-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序获取企业账单
        [WebMethod(Description = "正式版本")]
        public string xcx_companygetzd(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();

            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string biaodate = comrcv.Map_Args["biaodate"];
                string pageindex = comrcv.Map_Args["pageindex"];

                logJieKou.Info("企业小程序获取企业账单-" + companyaccount);
                int pagecount = 100;
                int intpageindex = 0;
                int.TryParse(pageindex, out intpageindex);
                intpageindex = intpageindex * pagecount;
                string limitstring = string.Format("limit {0},{1} ", intpageindex, pagecount);
                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("SELECT * FROM {0}" +
                    " where zf_status ='支付成功' AND zf_companyaccount='{1}' AND zf_comshouzhi <> '0' ORDER BY zf_time DESC {2} ;",
                    BIAOQGZHIFURECORD + biaodate, companyaccount, limitstring);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序进入验证-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }



        //企业小程序企业代收自提手续费
        [WebMethod(Description = "正式版本")]
        public string xcx_companydaishouztfg(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                string daishouztfeilv = comrcv.Map_Args["daishouztfeilv"];//代收自提的费率
                string daishouztminshouxu = comrcv.Map_Args["daishouztminshouxu"];//代收自提的最低手续费
                string daishouztopen = comrcv.Map_Args["daishouztopen"];//代收自提是否打开此功能,1为打开，0为关闭

                logJieKou.Info("企业小程序企业代收自提手续费-" + companyaccount);

                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("UPDATE {0} SET com_daishouztfeilv= '{1}',com_daishouztopen= '{2}',com_daishouminshouxu= '{3}'  " +
                     "WHERE com_account = '{4}'", BIAOQGZHIFUCOMPANY, daishouztfeilv, daishouztopen, daishouztminshouxu, companyaccount);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                mainsql.closesql();
                if (sqlret != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "修改失败";
                    goto EXIT;
                }



            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序企业代收自提手续费-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序查看企业关注用户
        [WebMethod(Description = "正式版本")]
        public string xcx_companygetuser(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                string pageindex = comrcv.Map_Args["pageindex"];

                logJieKou.Info("企业小程序查看企业关注用户-" + companyaccount);
                int pagecount = 100;
                int intpageindex = 0;
                int.TryParse(pageindex, out intpageindex);
                intpageindex = intpageindex * pagecount;
                string limitstring = string.Format("limit {0},{1} ", intpageindex, pagecount);
                mainsql.openYongHuServicesql();
                string sqlkey = " user_phone,user_name,user_address,user_renzhengstatus,user_renzhengpicname ";
                string sqlcmd = string.Format("SELECT {0} from {1} where user_bindcompany like '%{2}%' {3} ;",
                   sqlkey, BIAOYONGHUUSER, companyaccount, limitstring);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);

                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                sqlcmd = string.Format("SELECT COUNT(*) from {0} where user_bindcompany like '%{1}%' ;",
                    BIAOYONGHUUSER, companyaccount);
                string alluser = mainsql.SqlExcuteCountReturn(sqlcmd);
                ret.Map_Args.Add("AllUser", alluser);
                mainsql.closesql();
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序查看企业关注用户-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序查找企业关注用户
        [WebMethod(Description = "正式版本")]
        public string xcx_companyfinduser(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string tiaojian = comrcv.Map_Args["tiaojian"];


                logJieKou.Info("企业小程序查找企业关注用户-" + companyaccount);


                mainsql.openYongHuServicesql();
                string sqlkey = " * ";
                string sqlcmd = string.Format("SELECT {0} from {1} where user_bindcompany like '%{2}%' AND (user_phone like '%{3}%' OR user_name like '%{3}%' ) ;",
                   sqlkey, BIAOYONGHUUSER, companyaccount, tiaojian);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序查找企业关注用户-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序获取某公司所有的优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companygetcomyhqmodel(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                logJieKou.Info("企业小程序获取优惠券模板-" + companyaccount);

                mainsql.openYongHuServicesql();
                string sqlkey = " * ";
                string sqlcmd = string.Format("SELECT {0} from {1} where yhq_companyaccount = '{2}' ;",
                   sqlkey, BIAOCOMYOUHUIQUAN, companyaccount);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序获取优惠券模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序获取所有发布的优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companygetallyhqpubmodel(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {


                logJieKou.Info("企业小程序获取优惠券发布模板");

                mainsql.openYongHuServicesql();
                string sqlkey = " * ";
                string sqlcmd = string.Format("SELECT {0} from {1} where yhq_ispub = '1' ;",
                   sqlkey, BIAOCOMYOUHUIQUAN);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序获取优惠券发布模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序企业新建优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companycreateyhqmodel(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];



                string yhq_chugangname = comrcv.Map_Args["yhq_chugangname"];//为相关网点名称
                string yhq_chugangaccount = comrcv.Map_Args["yhq_chugangaccount"];//为相关网点账号
                string yhq_daogangname = comrcv.Map_Args["yhq_daogangname"];//为相关网点名称
                string yhq_daogangaccount = comrcv.Map_Args["yhq_daogangaccount"];//为相关网点账号

                string yhq_zftype = comrcv.Map_Args["yhq_zftype"];//1为通用支付，2为金币支付
                string yhq_type = comrcv.Map_Args["yhq_type"];//1为折扣券，2为满减券

                string yhq_endtime = comrcv.Map_Args["yhq_endtime"];
                string yhq_zhekou = comrcv.Map_Args["yhq_zhekou"];
                string yhq_manjianjian = comrcv.Map_Args["yhq_manjianjian"];
                string yhq_manjianman = comrcv.Map_Args["yhq_manjianman"];
                string yhq_useronedaymax = comrcv.Map_Args["yhq_useronedaymax"];
                string yhq_shuoming = "";

                logJieKou.Info("企业小程序企业新建优惠券模板-" + companyaccount);

                mainsql.openYongHuServicesql();
                Dictionary<string, string> mapargs = new Dictionary<string, string>();

                if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "公司不具备相关功能";
                    goto EXIT;
                }
                if (yhq_type == "1")
                {
                    yhq_shuoming = yhq_zhekou + "折";
                }
                else if (yhq_type == "2")
                {
                    yhq_shuoming = "满" + yhq_manjianman + "减" + yhq_manjianjian;
                }
                else
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "优惠券类型错误";
                    goto EXIT;
                }




                string sqlcmd = string.Format("INSERT INTO {0} (yhq_chugangname,yhq_chugangaccount,yhq_daogangname,yhq_daogangaccount,yhq_zftype,yhq_type ," +
                   "yhq_companyaccount,yhq_companyname,yhq_endtime,yhq_zhekou,yhq_manjianjian,yhq_manjianman,yhq_shuoming,yhq_useronedaymax,yhq_ispub)" +
                           " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','0')",
                          BIAOCOMYOUHUIQUAN, yhq_chugangname, yhq_chugangaccount, yhq_daogangname, yhq_daogangaccount, yhq_zftype, yhq_type,
                   companyaccount, mapargs["com_name"], yhq_endtime, yhq_zhekou, yhq_manjianjian, yhq_manjianman, yhq_shuoming, yhq_useronedaymax);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                mainsql.closesql();

                if (sqlret != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "新建模板失败";
                    goto EXIT;
                }

            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序企业新建优惠券模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序企业删除优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companydelyhqmodel(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                string Sid = comrcv.Map_Args["Sid"];


                logJieKou.Info("企业小程序企业删除优惠券模板-" + companyaccount);

                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("delete  from {0} where  Sid ='{1}' AND yhq_companyaccount='{2}' ;",
                            BIAOCOMYOUHUIQUAN, Sid, companyaccount);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                mainsql.closesql();
                if (sqlret != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "删除模板失败";
                    goto EXIT;
                }



            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序企业删除优惠券模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序企业发布优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companyyhqmodel_pub(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                string Sid = comrcv.Map_Args["Sid"];

                logJieKou.Info("企业小程序企业发布优惠券模板-" + companyaccount);

                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("UPDATE {0} SET yhq_ispub='1' where  Sid ='{1}' AND yhq_companyaccount='{2}' ;",
                            BIAOCOMYOUHUIQUAN, Sid, companyaccount);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                mainsql.closesql();
                if (sqlret != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "发布优惠券模板失败";
                    goto EXIT;
                }



            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序企业删除优惠券模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业小程序企业取消发布优惠券模板
        [WebMethod(Description = "正式版本")]
        public string xcx_companyyhqmodel_upub(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];

                string Sid = comrcv.Map_Args["Sid"];

                logJieKou.Info("企业小程序企业取消发布优惠券模板-" + companyaccount);

                mainsql.openYongHuServicesql();

                string sqlcmd = string.Format("UPDATE {0} SET yhq_ispub='0' where  Sid ='{1}' AND yhq_companyaccount='{2}' ;",
                            BIAOCOMYOUHUIQUAN, Sid, companyaccount);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                mainsql.closesql();
                if (sqlret != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "取消发布优惠券模板失败";
                    goto EXIT;
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("企业小程序企业取消发布优惠券模板-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //用户自己领取优惠券
        [WebMethod(Description = "正式版本")]
        public string xcx_usergetyhq(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string phone = comrcv.Map_Args["phone"];
                string yhqmodelsid = comrcv.Map_Args["yhqmodelsid"];

                logJieKou.Info("用户自己领取优惠券-" + companyaccount);

                using (TransactionScope tsall = new TransactionScope())
                {
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("SELECT * from {0} where yhq_ispub = '1' AND Sid='{1}' AND  yhq_companyaccount='{2}' ;",
                    BIAOCOMYOUHUIQUAN, yhqmodelsid, companyaccount);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "获取优惠券模板失败";
                        goto EXIT;
                    }


                    DataRow modelrow = ds.Rows[0] as DataRow;

                    int yhq_useronedaymax = 0;
                    int.TryParse(modelrow["yhq_useronedaymax"].ToString(), out yhq_useronedaymax);
                    if (yhq_useronedaymax != 0)
                    {
                        string thisday = DateTime.Now.ToString("yyyyMMdd");
                        sqlcmd = string.Format("SELECT * from {0} where yhq_yhqmodelsid = '{1}' AND yhq_createtime='{2}' AND  yhq_userphone='{3}' ;",
                        BIAOALLYOUHUIQUAN, modelrow["Sid"].ToString(), thisday, phone);
                        ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count >= yhq_useronedaymax)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "已经超过当日可领取的优惠券数量";
                            goto EXIT;
                        }
                    }


                    string yhqid = GetYHQID();
                    sqlcmd = string.Format("INSERT INTO {0} (yhq_yhqid,yhq_userphone,yhq_chugangname,yhq_chugangaccount,yhq_daogangname,yhq_daogangaccount,yhq_zftype,yhq_type ," +
                        "yhq_status,yhq_companyaccount,yhq_companyname,yhq_endtime,yhq_zhekou,yhq_manjianjian,yhq_manjianman,yhq_shuoming,yhq_yhqmodelsid,yhq_createtime)" +
                        " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}')",
                        BIAOALLYOUHUIQUAN, yhqid, phone, modelrow["yhq_chugangname"], modelrow["yhq_chugangaccount"],
                        modelrow["yhq_daogangname"], modelrow["yhq_daogangaccount"], modelrow["yhq_zftype"], modelrow["yhq_type"], "未使用",
                        modelrow["yhq_companyaccount"], modelrow["yhq_companyname"], modelrow["yhq_endtime"], modelrow["yhq_zhekou"],
                        modelrow["yhq_manjianjian"], modelrow["yhq_manjianman"], modelrow["yhq_shuoming"], modelrow["Sid"], DateTime.Now.ToString("yyyyMMdd"));
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    mainsql.closesql();
                    if (sqlret != 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "领取优惠券失败";
                        goto EXIT;
                    }
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("用户自己领取优惠券-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //企业赠送优惠券给用户
        [WebMethod(Description = "正式版本")]
        public string xcx_comgiveuseryhq(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string phonelist = comrcv.Map_Args["phonelist"];//15023196534,15023196535
                string yhqmodelsid = comrcv.Map_Args["yhqmodelsid"];

                logJieKou.Info("企业赠送优惠券给用户-" + companyaccount);
                using (TransactionScope tsall = new TransactionScope())
                {
                    mainsql.openYongHuServicesql();

                    string sqlcmd = string.Format("SELECT * from {0} where Sid='{1}' AND  yhq_companyaccount='{2}' ;",
                    BIAOCOMYOUHUIQUAN, yhqmodelsid, companyaccount);

                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "获取优惠券模板失败";
                        goto EXIT;
                    }

                    DataRow modelrow = ds.Rows[0] as DataRow;



                    string[] phoneArr = phonelist.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                    for (int i = 0; i < phoneArr.Length; i++)
                    {
                        string yhqid = GetYHQID();
                        if (phoneArr[i].Length == 11)
                        {
                            sqlcmd = string.Format("INSERT INTO {0} (yhq_yhqid,yhq_userphone,yhq_chugangname,yhq_chugangaccount,yhq_daogangname,yhq_daogangaccount,yhq_zftype,yhq_type ," +
                            "yhq_status,yhq_companyaccount,yhq_companyname,yhq_endtime,yhq_zhekou,yhq_manjianjian,yhq_manjianman,yhq_shuoming,yhq_createtime)" +
                            " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}')",
                            BIAOALLYOUHUIQUAN, yhqid, phoneArr[i], modelrow["yhq_chugangname"], modelrow["yhq_chugangaccount"],
                            modelrow["yhq_daogangname"], modelrow["yhq_daogangaccount"], modelrow["yhq_zftype"], modelrow["yhq_type"], "未使用",
                            modelrow["yhq_companyaccount"], modelrow["yhq_companyname"], modelrow["yhq_endtime"], modelrow["yhq_zhekou"],
                            modelrow["yhq_manjianjian"], modelrow["yhq_manjianman"], modelrow["yhq_shuoming"], DateTime.Now.ToString("yyyyMMdd"));
                            int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                            if (sqlret != 1)
                            {
                                mainsql.closesql();
                                ret.Map_Args["ErrorMsg"] = "领取优惠券失败";
                                goto EXIT;
                            }
                        }
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("用户自己领取优惠券-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //公司请求充值零钱
        [WebMethod(Description = "正式版本")]
        public string xcx_comaskchongzhi_lq(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            string qgliushuinumber = "";
            try
            {
                logJieKou.Info("公司请求充值零钱-");
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string jine = comrcv.Map_Args["cost"];                      //金额
                string openid = comrcv.Map_Args["openid"];
                string phone = comrcv.Map_Args["phone"];
                string chbusinessrecordnumber = "";
                string companynumber = "";
                string companyname = "";
                string com_comfeilv = "";
                string com_minshouxu = "";
                string companydate = "";

                #region 查支付公司表的信息

                mainsql.openYongHuServicesql();
                Dictionary<string, string> mapargs = new Dictionary<string, string>();

                if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "该公司未开通相关功能";  //参数错误
                    goto EXIT;
                }

                string QGFEILVSTR = mapargs["qgfeilv"];
                string QGMINSHOUXUSTR = mapargs["qgminshouxu"];
                double.TryParse(QGFEILVSTR, out QGFEILV);
                double.TryParse(QGMINSHOUXUSTR, out QGMINSHOUXU);

                companydate = mapargs["com_numberdate"];
                companyname = mapargs["com_name"];
                companynumber = mapargs["com_number"];
                com_comfeilv = mapargs["com_comfeilv"];
                com_minshouxu = mapargs["com_minshouxu"];
                qgliushuinumber = GetCompanyDDNumber(mainsql, companydate, companyaccount);
                //生成青贯流水号
                qgliushuinumber = companynumber + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;

                mainsql.closesql();
                #endregion



                #region 调用传化接口

                string subjectstring = companyname + "-企业充值零钱";
                string logip = "";
                try
                {
                    logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                }
                catch
                { }

                Dictionary<string, string> zfmapargs = new Dictionary<string, string>();
                zfmapargs.Add("subjectstring", subjectstring);
                zfmapargs.Add("logip", logip);
                zfmapargs.Add("companyname", companyname);
                zfmapargs.Add("qgliushuinumber", qgliushuinumber);
                zfmapargs.Add("jine", jine);
                zfmapargs.Add("openid", openid);
                zfmapargs.Add("ErrorMsg", "无错误");
                if (CH_ZHIFU_COMMON(ref zfmapargs) == true)
                {
                    ret.Map_Args["appId"] = zfmapargs["appId"];
                    ret.Map_Args["timeStamp"] = zfmapargs["timeStamp"];
                    ret.Map_Args["nonceStr"] = zfmapargs["nonceStr"];
                    ret.Map_Args["package"] = zfmapargs["package"];
                    ret.Map_Args["signType"] = zfmapargs["signType"];
                    ret.Map_Args["paySign"] = zfmapargs["paySign"];
                    ret.Map_Args["qgliushuinumber"] = qgliushuinumber;
                    chbusinessrecordnumber = zfmapargs["chbusinessrecordnumber"];
                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = zfmapargs["ErrorMsg"];   //参数错误
                    goto EXIT;

                }
                #endregion

                #region 生成账单记录表
                //计算相关金额
                double yonghujine = 0;   //支付的金额
                double qgjine = 0;       //青贯得到的金额
                double lqjine = 0;       //用户得到的金额


                double lqfeilvdb = 0;     //公司零钱的比例
                double lqminshouxudb = 0; //公司收零钱最小的手续费



                double.TryParse(jine, out yonghujine);

                double.TryParse(com_comfeilv, out lqfeilvdb);
                double.TryParse(com_minshouxu, out lqminshouxudb);

                if (yonghujine == 0)
                {
                    ret.Map_Args["ErrorMsg"] = "金额或者该公司配置文件错误";  //参数错误
                    goto EXIT;
                }

                if (yonghujine <= lqminshouxudb)
                {
                    ret.Map_Args["ErrorMsg"] = "订单金额不能小于等于【" + lqminshouxudb.ToString("0.00") + "】元";  //参数错误
                    goto EXIT;
                }

                double qgjineshouxu = yonghujine * QGFEILV;
                qgjineshouxu = Math.Round(qgjineshouxu, 2);//将手续费变成两位小数

                if (qgjineshouxu < QGMINSHOUXU)
                {
                    qgjineshouxu = QGMINSHOUXU;
                }
                qgjine = yonghujine - qgjineshouxu;

                double lqjineshouxu = yonghujine * lqfeilvdb;
                lqjineshouxu = Math.Round(lqjineshouxu, 2);//将手续费变成两位小数

                if (lqjineshouxu < lqminshouxudb)
                {
                    lqjineshouxu = lqminshouxudb;
                }
                lqjine = yonghujine - lqjineshouxu;

                mainsql.openYongHuServicesql();

                string defaultstring = string.Format("充值{1}元得到{2}元零钱！", companyname, yonghujine.ToString(), lqjine.ToString());

                string sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_companyaccount," +
                    "zf_companynumber,zf_companyname,zf_companyamount,zf_qgamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi)" +
                    " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','零钱','0','1')",
                   BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "公司充值零钱", "等待支付", qgliushuinumber,
                   chbusinessrecordnumber, companyaccount, companynumber, companyname, lqjine.ToString("0.00"),
                   qgjine.ToString("0.00"), defaultstring, phone);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                if (sqlret != 1)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "插入记录失败";  //参数错误
                    goto EXIT;
                }
                ret.Map_Args.Add("RetMsg", string.Format("根据公司【{0}】的设置，您充值{1}元将会得到{2}元零钱！", companyname, yonghujine.ToString(), lqjine.ToString()));

                mainsql.closesql();

                #endregion

            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //公司请求充值零钱OK
        [WebMethod(Description = "正式版本")]
        public string xcx_comchongzhi_lqok(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string qgliushuinumber = comrcv.Map_Args["qgliushuinumber"];
                string companyrealtimebalance = "0";
                string qgrealtimebalance = "0";

                #region 查支付公司表的信息


                mainsql.openYongHuServicesql();

                Dictionary<string, string> mapargs = new Dictionary<string, string>();

                if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "该公司未开通相关功能";  //参数错误
                    goto EXIT;
                }
                qgrealtimebalance = mapargs["qgamount"];       //青贯的余额
                companyrealtimebalance = mapargs["com_amount"];     //对应公司的余额

                mainsql.closesql();

                #endregion

                #region 修改账单记录表
                using (TransactionScope tsall1 = new TransactionScope())
                {
                    mainsql.openYongHuServicesql();
                    string biaodate = qgliushuinumber.Substring(5, 6);
                    string sqlcmd = string.Format("SELECT * from {0} where zf_qgnumber='{1}' AND zf_status='等待支付' AND  zf_companyaccount='{2}' ;",
                        BIAOQGZHIFURECORD + biaodate, qgliushuinumber, companyaccount);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "没有相应的流水";                                          //参数错误
                        goto EXIT;
                    }
                    string zf_qgamount = ds.Rows[0]["zf_qgamount"].ToString();
                    string zf_companyamount = ds.Rows[0]["zf_companyamount"].ToString();




                    double qgamount = 0;
                    double.TryParse(zf_qgamount, out qgamount);//青贯得到的金额
                    double dbqgrealtimebalance = 0;
                    double.TryParse(qgrealtimebalance, out dbqgrealtimebalance);//青贯得到的金额
                    dbqgrealtimebalance += qgamount;

                    double comamount = 0;
                    double.TryParse(zf_companyamount, out comamount);//对应用户的金额
                    double dbcomrealtimebalance = 0;
                    double.TryParse(companyrealtimebalance, out dbcomrealtimebalance);//用户得到的金额
                    dbcomrealtimebalance += comamount;





                    sqlcmd = string.Format("update {0} set zf_status='支付成功',zf_qgrealtimebalance='{1}'," +
                        "zf_companyrealtimebalance='{2}'  where zf_qgnumber='{3}' ",
                        BIAOQGZHIFURECORD + biaodate, dbqgrealtimebalance.ToString("0.00"),
                        dbcomrealtimebalance.ToString("0.00"), qgliushuinumber);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改支付记录失败";  //参数错误
                        goto EXIT;
                    }

                    sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='qingguan' AND com_number='00000' ",
                    BIAOQGZHIFUCOMPANY, dbqgrealtimebalance.ToString("0.00"));
                    sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改青贯账目失败";  //参数错误
                        goto EXIT;
                    }


                    sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='{2}'  ",
                    BIAOQGZHIFUCOMPANY, dbcomrealtimebalance.ToString("0.00"), companyaccount);
                    sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改青贯账目失败";  //参数错误
                        goto EXIT;
                    }


                    mainsql.closesql();
                    tsall1.Complete();
                }
                #endregion
            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //公司请求零钱提现
        [WebMethod(Description = "正式版本")]
        public string xcx_comasktixian_lq(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            string qgliushuinumber = "";
            try
            {
                logJieKou.Info("公司请求零钱提现-");
                string companyaccount = comrcv.Map_Args["companyaccount"];
                string jine = comrcv.Map_Args["cost"];                      //金额
                string openid = comrcv.Map_Args["openid"];
                string phone = comrcv.Map_Args["phone"];
                string bankname = comrcv.Map_Args["bankname"];
                string username = comrcv.Map_Args["username"];
                string bankcardid = comrcv.Map_Args["bankcardid"];
                string chbusinessrecordnumber = "";
                string companynumber = "";
                string companyname = "";
                string companydate = "";


                using (TransactionScope tsall1 = new TransactionScope())
                {
                    #region 查支付公司表的信息


                    mainsql.openYongHuServicesql();
                    Dictionary<string, string> mapargs = new Dictionary<string, string>();

                    if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "支付系统配置表错误";  //参数错误
                        goto EXIT;
                    }

                    string qgrealtimebalance = mapargs["qgamount"];       //青贯的余额
                    string companyrealtimebalance = mapargs["com_amount"];     //对应公司的余额

                    companydate = mapargs["com_numberdate"];
                    companyname = mapargs["com_name"];
                    companynumber = mapargs["com_number"];
                    qgliushuinumber = GetCompanyDDNumber(mainsql, companydate, companyaccount);
                    //生成青贯流水号
                    qgliushuinumber = companynumber + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;

                    #endregion

                    #region 计算和插入表

                    //计算相关金额

                    double qgjine = 0;       //青贯的金额
                    double comjine = 0;       //用户的金额

                    double txjine = 0;       //提现的金额

                    double.TryParse(jine, out txjine);
                    double.TryParse(companyrealtimebalance, out comjine);
                    double.TryParse(qgrealtimebalance, out qgjine);

                    if (comjine < txjine)
                    {
                        ret.Map_Args["ErrorMsg"] = "公司余额不足";  //参数错误
                        goto EXIT;
                    }

                    if (qgjine < txjine)
                    {
                        ret.Map_Args["ErrorMsg"] = "青贯余额不足";  //参数错误
                        goto EXIT;
                    }


                    //生成账单记录表


                    string sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_companyaccount," +
                    "zf_companynumber,zf_companyname,zf_companyamount,zf_qgamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi)" +
                    " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','零钱','0','2')",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "公司零钱提现", "等待支付", qgliushuinumber,
                    chbusinessrecordnumber, companyaccount, companynumber, companyname, txjine.ToString("0.00"), txjine.ToString("0.00"), "公司零钱提现", phone);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "插入记录失败";
                        goto EXIT;
                    }
                    mainsql.closesql();
                    tsall1.Complete();
                    #endregion
                }

                #region 调用传化接口

                string subjectstring = companyname + "-公司提现";
                string qgppid = QGZHIFUQGAPPID;
                string chappid = QGZHIFUCHAPPID;
                string sk = QGZHIFUCHSK;
                string com_accountnumber = QGZHIFUACCOUNTNUMBER;

                string logip = "";
                try
                {
                    logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                }
                catch
                { }
                String service_id = "tf56enterprise.enterprise.payForCustomer";
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                paramMap.Add("appid", chappid);
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                paramMap.Add("service_id", service_id);
                paramMap.Add("sign_type", "RSA");
                paramMap.Add("businessnumber", qgliushuinumber);
                paramMap.Add("subject", "代收款提现");
                paramMap.Add("transactionamount", jine);
                paramMap.Add("bankcardnumber", bankcardid);
                paramMap.Add("bankcardname", username);
                paramMap.Add("bankname", bankname);
                paramMap.Add("bankcardtype", "个人");
                paramMap.Add("bankaccounttype", "储蓄卡");
                paramMap.Add("backurl", XCXBACKURL);
                paramMap.Add("fromaccountnumber", com_accountnumber);
                paramMap.Add("terminal", "Android");
                string tf_sign = signForm(paramMap, sk);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string retsult = PostWebRequestForm(baseurl, paramMap);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                logJieKou.Info("结果数据：\n" + retsultJson.ToString());
                string coderel = retsultJson["code"].ToString();
                string result = retsultJson["result"].ToString();
                string cuomsg = retsultJson["msg"].ToString();
                string retdata = retsultJson["data"].ToString();
                ret.Map_Args["ErrorMsg"] = cuomsg;
                logJieKou.Info("结果数据：\n" + result.ToString());
                if (result.Equals("success"))
                {
                    JObject alldataJson = JsonConvert.DeserializeObject(retdata) as JObject;
                    chbusinessrecordnumber = alldataJson["businessrecordnumber"].ToString();
                    //定时查询支付状态  
                    int count = CHAXUNTIME;
                    int interval = 1000;
                    ret.Map_Args["ErrorMsg"] = "处理中";
                    mainsql.openYongHuServicesql();
                    for (int i = 1; i <= count; i++)
                    {
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}' ;",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgliushuinumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            ret.Map_Args["ErrorMsg"] = "没有流水记录";
                            goto EXIT;
                        }

                        string zf_status = ds.Rows[0]["zf_status"].ToString();
                        if (zf_status.Equals("支付成功"))
                        {
                            ret.Byte_Flag = (sbyte)1;
                            mainsql.closesql();
                            ds.Dispose();
                            goto EXIT;
                        }
                        else if (zf_status.Equals("支付失败"))
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            ret.Map_Args["ErrorMsg"] = ds.Rows[0]["zf_default"].ToString();
                            goto EXIT;
                        }
                        Thread.Sleep(interval);
                    }
                    mainsql.closesql();

                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = "聚合支付返回错误信息" + cuomsg;  //参数错误
                    goto EXIT;
                }

                #endregion

            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //公司获取所有外部的账务信息，金币，零钱，积分。
        [WebMethod(Description = "正式版本")]
        public string xcx_comgetalluserfinance(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();

            try
            {

                mainsql.openYongHuServicesql();

                string companyaccount = comrcv.Map_Args["companyaccount"];

                logJieKou.Info("公司获取所有外部的账务信息-" + companyaccount);



                string sqlcmd = string.Format("SELECT SUM(fin_jinbi) as alljinbi,SUM(fin_jifen) as alljifen  FROM {0}  where fin_companyaccount='{1}'   ;",
                    BIAOALLFINANCE, companyaccount);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                mainsql.closesql();
            }
            catch (Exception ex)
            {
                logJieKou.Info("公司获取所有外部的账务信息-" + ex.Message);
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }


        #endregion

        #region 商户小程序相关

        #region 传化回调

        //小程序回调
        [WebMethod(Description = "小程序回调")]
        public void ModA_XcxHuiDiao()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";
            JObject ret = JObject.Parse(result);


            System.IO.Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            postContent = HttpUtility.UrlDecode(postContent);
            logJieKou.Info("小程序回调开始：" + "-" + postContent);

            try
            {
                Dictionary<string, string> mapargs = new Dictionary<string, string>();
                string[] postArr = postContent.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < postArr.Length; i++)
                {
                    string[] proArr = postArr[i].Split(new string[] { "=" }, StringSplitOptions.None);
                    if (proArr.Length > 1)
                    {
                        mapargs.Add(proArr[0], proArr[1]);
                    }
                }

                string liushuinumber = mapargs["businessnumber"];// info.businessnumber;
                string zhifunumber = mapargs["businessrecordnumber"];// info.businessrecordnumber;
                string companycode = liushuinumber.Substring(0, 5);
                string zhifustatus = mapargs["status"]; //info.status;
                string zhifuren = mapargs["fromaccountnumber"];// info.fromaccountnumber;

                if (zhifustatus.Equals("成功"))
                {
                    zhifustatus = "支付成功";
                }
                else if (zhifustatus.Equals("失败"))
                {
                    zhifustatus = "支付失败";
                }
                else if (zhifustatus.Equals("已退款"))
                {
                    zhifustatus = "已退款";
                }
                //transactionamount = 0.01

                mysqlcli mainsql = new mysqlcli();
                mainsql.openYongHuServicesql();
                string datestr = DateTime.Now.ToString("yyyyMM");
                string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'; ",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), liushuinumber);

                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    logJieKou.Info("支付回调Error：" + sqlcmd);
                    mainsql.closesql();
                    ds.Dispose();
                    goto EXIT;
                }
                logJieKou.Info($"处理团购逻辑{zhifustatus == "支付成功"},{ds.Rows[0]["zf_type"].ToString() == "团购支付"}");
                if (ds.Rows[0]["zf_type"].ToString() == "零钱提现")
                {
                    string remark = mapargs["remark"];// info.fromaccountnumber;

                    mapargs = new Dictionary<string, string>();
                    mapargs.Add("qgnumber", liushuinumber);
                    mapargs.Add("chnumber", zhifunumber);
                    mapargs.Add("zhifustatus", zhifustatus);
                    mapargs.Add("remark", remark);
                    if (lq_tixianhuidiao(mapargs) == false)
                    {
                        logJieKou.Info("代付回调错误退出");
                    }
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "公司零钱提现")
                {
                    string remark = mapargs["remark"];// info.fromaccountnumber;

                    mapargs = new Dictionary<string, string>();
                    mapargs.Add("qgnumber", liushuinumber);
                    mapargs.Add("chnumber", zhifunumber);
                    mapargs.Add("zhifustatus", zhifustatus);
                    mapargs.Add("remark", remark);
                    if (lqcom_tixianhuidiao(mapargs) == false)
                    {
                        logJieKou.Info("代付回调错误退出");
                    }
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "商户零钱提现")
                {
                    string remark = mapargs["remark"];// info.fromaccountnumber;

                    mapargs = new Dictionary<string, string>();
                    mapargs.Add("qgnumber", liushuinumber);
                    mapargs.Add("chnumber", zhifunumber);
                    mapargs.Add("zhifustatus", zhifustatus);
                    mapargs.Add("remark", remark);
                    if (lqsh_tixianhuidiao(mapargs) == false)
                    {
                        logJieKou.Info("代付回调错误退出");
                    }
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "修理厂零钱提现")
                {
                    string remark = mapargs["remark"];// info.fromaccountnumber;

                    mapargs = new Dictionary<string, string>();
                    mapargs.Add("qgnumber", liushuinumber);
                    mapargs.Add("chnumber", zhifunumber);
                    mapargs.Add("zhifustatus", zhifustatus);
                    mapargs.Add("remark", remark);
                    if (lqxlc_tixianhuidiao(mapargs) == false)
                    {
                        logJieKou.Info("代付回调错误退出");
                    }
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "用户零钱提现")
                {
                    string remark = mapargs["remark"];// info.fromaccountnumber;

                    mapargs = new Dictionary<string, string>();
                    mapargs.Add("qgnumber", liushuinumber);
                    mapargs.Add("chnumber", zhifunumber);
                    mapargs.Add("zhifustatus", zhifustatus);
                    mapargs.Add("remark", remark);
                    if (lqyh_tixianhuidiao(mapargs) == false)
                    {
                        logJieKou.Info("代付回调错误退出");
                    }
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "商品支付")
                {
                    shop_huidiao(ds.Rows[0]["zf_biaoid"].ToString(), liushuinumber, zhifustatus == "支付成功");
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "维修支付")
                {
                    weixiu_huidiao(ds.Rows[0]["zf_biaoid"].ToString(), liushuinumber, zhifustatus == "支付成功");
                }
                else if (ds.Rows[0]["zf_type"].ToString() == "团购支付")
                {
                    var orders = ds.ToModels();
                    var orderIds = string.Join(",", orders.Select(x => x["zf_biaoid"]));

                    tuangou_huidiao(orderIds, liushuinumber, zhifustatus == "支付成功", logJieKou);
                }
                mainsql.closesql();

            }
            catch (Exception ex)
            {
                logJieKou.Info("回调Error：" + ex.Message);
            }

            EXIT:
            logJieKou.Info("回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }


        //小程序退款回调
        [WebMethod(Description = "小程序退款回调")]
        public void ModA_XcxHuiDiaoRefund()
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            string result = @"{ 
                     'result':'success',  
                     'msg':'请求成功'
                 }";

            JObject ret = JObject.Parse(result);
            Stream postData = Context.Request.InputStream;
            StreamReader sRead = new StreamReader(postData);
            string postContent = sRead.ReadToEnd();
            postContent = HttpUtility.UrlDecode(postContent);
            logJieKou.Info("小程序退款回调开始：" + "-" + postContent);

            try
            {
                mysqlcli mainsql = new mysqlcli();
                mainsql.openYongHuServicesql();

                using (TransactionScope tsall = new TransactionScope())
                {
                    Dictionary<string, string> mapargs = new Dictionary<string, string>();
                    string[] postArr = postContent.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < postArr.Length; i++)
                    {
                        string[] proArr = postArr[i].Split(new string[] { "=" }, StringSplitOptions.None);
                        if (proArr.Length > 1)
                        {
                            mapargs.Add(proArr[0], proArr[1]);
                        }
                    }

                    string liushuinumber = mapargs["businessnumber"];
                    string zhifunumber = mapargs["businessrecordnumber"];
                    string tableName = liushuinumber.Substring(5, 6);
                    string transactiontype = mapargs["transactiontype"];
                    string zhifuren = mapargs["fromaccountnumber"];

                    if (transactiontype.Equals("退款"))
                    {
                        transactiontype = "已退款";
                        string sqlcmd = string.Format("select * from {0} where zf_qgrefundnumber = '{1}'; ",
                            BIAOQGZHIFURECORD + tableName, liushuinumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);

                        if (ds.Rows.Count == 0)
                        {
                            logJieKou.Info("未找到订单流水：" + sqlcmd);
                            goto EXIT;
                        }

                        var buy_order_id = ds.Rows[0]["zf_biaoid"];//商品订单ID
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@orderId", buy_order_id));
                        var sql = "update s_commoditybuyorder set buy_order_pay_status=4,buy_order_update_time=NOW() where buy_order_id=@orderId;";

                        var num = mainsql.SqlExcuteNoReturn(sql, paras.ToArray());
                        if (num < 1)
                        {
                            logJieKou.Info("退款回调订单状态Error：" + sql);
                        }

                        //修改流水支付状态
                        sql = string.Format("update {0} set zf_status='{1}' where zf_qgrefundnumber='{2}' ",
                         BIAOQGZHIFURECORD + tableName, transactiontype, liushuinumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sql);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("退款回调流水状态Error：" + sql);
                        }
                    }

                    mainsql.closesql();
                    tsall.Complete();

                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("回调Error：" + ex.Message);
            }

            EXIT:
            logJieKou.Info("回调结束：" + ret.ToString());
            Context.Response.Charset = "UTF-8";
            Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Context.Response.Write(ret.ToString());
            Context.Response.End();
        }

        //零钱回调
        public bool lq_tixianhuidiao(Dictionary<string, string> mapargs)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string qgnumber = mapargs["qgnumber"];
                string chnumber = mapargs["chnumber"];
                string zhifustatus = mapargs["zhifustatus"];
                string remark = mapargs["remark"];
                if (zhifustatus == "支付成功")
                {
                    using (TransactionScope tsall1 = new TransactionScope())
                    {
                        mysqlcli mainsql = new mysqlcli();
                        mainsql.openYongHuServicesql();
                        string datestr = DateTime.Now.ToString("yyyyMM");
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'  ",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgnumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            ds.Dispose();
                            return false;
                        }
                        string companyaccount = ds.Rows[0]["zf_companyaccount"].ToString();
                        string phone = ds.Rows[0]["zf_zfphone"].ToString();
                        string jine = ds.Rows[0]["zf_yhamount"].ToString();
                        //获取余额
                        mapargs = new Dictionary<string, string>();

                        if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                        {
                            mainsql.closesql();
                            return false;
                        }

                        string qgrealtimebalance = mapargs["qgamount"];       //青贯的余额



                        sqlcmd = string.Format("SELECT * from {0} where fin_userphone='{1}' AND fin_companyaccount='{2}' ;", BIAOALLFINANCE, phone, companyaccount);
                        ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }
                        string lqrealtimebalance = ds.Rows[0]["fin_lingqian"].ToString();                            //青贯的零钱余额
                                                                                                                     //获取余额

                        //计算相关金额
                        double lqjine = 0;       //用户的金额                                                                                

                        double qgjine = 0;       //青贯的金额
                        double lqrealtimebalancedb = 0;//用户的余额



                        double.TryParse(jine, out lqjine);
                        double.TryParse(lqrealtimebalance, out lqrealtimebalancedb);
                        double.TryParse(qgrealtimebalance, out qgjine);


                        if (lqrealtimebalancedb < lqjine) //用户余额不足
                        {
                            mainsql.closesql();
                            return false;
                        }

                        if (qgjine < lqjine)//青贯余额不足
                        {
                            mainsql.closesql();
                            return false;
                        }
                        lqrealtimebalancedb = lqrealtimebalancedb - lqjine;
                        qgjine = qgjine - lqjine;




                        sqlcmd = string.Format("UPDATE {0} SET zf_yhrealtimebalance='{1}'," +
                            "zf_qgrealtimebalance='{2}',zf_status='支付成功',zf_chnumber='{3}' " +
                        " WHERE zf_qgnumber = '{4}' ;",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), lqrealtimebalancedb.ToString("0.00"),
                        qgjine.ToString("0.00"), chnumber, qgnumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }



                        sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='qingguan' AND com_number='00000' ",
                        BIAOQGZHIFUCOMPANY, qgjine.ToString("0.00"));
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set fin_lingqian='{1}'   where fin_userphone='{2}' AND fin_companyaccount='{3}' ",
                        BIAOALLFINANCE, lqrealtimebalancedb.ToString("0.00"), phone, companyaccount);
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }
                        mainsql.closesql();
                        tsall1.Complete();
                    }
                }
                else
                {
                    mysqlcli mainsql = new mysqlcli();
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("UPDATE {0} SET zf_status='支付失败',zf_default='{1}' " +
                    " WHERE zf_qgnumber = '{2}' ;",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), remark, qgnumber);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        logJieKou.Info("零钱回调错误：" + sqlcmd);
                        mainsql.closesql();
                        return false;
                    }
                    mainsql.closesql();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("零钱回调错误：" + ex.Message);
            }
            return true;
        }

        //公司零钱回调
        public bool lqcom_tixianhuidiao(Dictionary<string, string> mapargs)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string qgnumber = mapargs["qgnumber"];
                string chnumber = mapargs["chnumber"];
                string zhifustatus = mapargs["zhifustatus"];
                string remark = mapargs["remark"];
                if (zhifustatus == "支付成功")
                {
                    using (TransactionScope tsall1 = new TransactionScope())
                    {
                        mysqlcli mainsql = new mysqlcli();
                        mainsql.openYongHuServicesql();
                        string datestr = DateTime.Now.ToString("yyyyMM");
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'  ",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgnumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            ds.Dispose();
                            return false;
                        }
                        string companyaccount = ds.Rows[0]["zf_companyaccount"].ToString();
                        string phone = ds.Rows[0]["zf_zfphone"].ToString();
                        string jine = ds.Rows[0]["zf_companyamount"].ToString();
                        //获取余额
                        mapargs = new Dictionary<string, string>();

                        if (CheckZhiFuComBiao(mainsql, companyaccount, ref mapargs) == false)
                        {
                            mainsql.closesql();
                            return false;
                        }

                        string qgrealtimebalance = mapargs["qgamount"];       //青贯的余额
                        string companyrealtimebalance = mapargs["com_amount"];     //对应公司的余额

                        //计算相关金额
                        double lqjine = 0;       //用户的金额                                                                                
                        double companyjine = 0;   //公司的金额
                        double qgjine = 0;       //青贯的金额
                        double.TryParse(jine, out lqjine);
                        double.TryParse(qgrealtimebalance, out qgjine);
                        double.TryParse(companyrealtimebalance, out companyjine);


                        if (companyjine < lqjine)//公司余额不足
                        {
                            mainsql.closesql();
                            return false;
                        }
                        if (qgjine < lqjine)//青贯余额不足
                        {
                            mainsql.closesql();
                            return false;
                        }

                        qgjine = qgjine - lqjine;
                        companyjine = companyjine - lqjine;



                        sqlcmd = string.Format("UPDATE {0} SET " +
                            "zf_qgrealtimebalance='{1}',zf_companyrealtimebalance='{2}',zf_status='支付成功',zf_chnumber='{3}' " +
                        " WHERE zf_qgnumber = '{4}' ;",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"),
                        qgjine.ToString("0.00"), companyjine.ToString("0.00"), chnumber, qgnumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='{2}' ",
                            BIAOQGZHIFUCOMPANY, companyjine.ToString("0.00"), companyaccount);
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='qingguan' AND com_number='00000' ",
                        BIAOQGZHIFUCOMPANY, qgjine.ToString("0.00"));
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }


                        mainsql.closesql();
                        tsall1.Complete();
                    }
                }
                else
                {
                    mysqlcli mainsql = new mysqlcli();
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("UPDATE {0} SET zf_status='支付失败',zf_default='{1}' " +
                    " WHERE zf_qgnumber = '{2}' ;",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), remark, qgnumber);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        logJieKou.Info("零钱回调错误：" + sqlcmd);
                        mainsql.closesql();
                        return false;
                    }
                    mainsql.closesql();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("零钱回调错误：" + ex.Message);
            }
            return true;
        }

        //商户零钱回调
        public bool lqsh_tixianhuidiao(Dictionary<string, string> mapargs)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string qgnumber = mapargs["qgnumber"];
                string chnumber = mapargs["chnumber"];
                string zhifustatus = mapargs["zhifustatus"];
                string remark = mapargs["remark"];
                if (zhifustatus == "支付成功")
                {
                    using (TransactionScope tsall1 = new TransactionScope())
                    {
                        mysqlcli mainsql = new mysqlcli();
                        mainsql.openYongHuServicesql();
                        string datestr = DateTime.Now.ToString("yyyyMM");
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'  ",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgnumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            ds.Dispose();
                            return false;
                        }
                        string companyaccount = ds.Rows[0]["zf_companyaccount"].ToString();
                        string phone = ds.Rows[0]["zf_zfphone"].ToString();
                        string jine = ds.Rows[0]["zf_companyamount"].ToString();
                        //获取余额
                        mapargs = new Dictionary<string, string>();

                        if (CheckZhiFuSHIDBiao(mainsql, companyaccount, ref mapargs) == false)
                        {
                            mainsql.closesql();
                            return false;
                        }


                        string shop_balance = mapargs["shop_balance"];     //对应公司的余额

                        //计算相关金额
                        double lqjine = 0;       //用户的金额                                                                                
                        double companyjine = 0;   //公司的金额

                        double.TryParse(jine, out lqjine);

                        double.TryParse(shop_balance, out companyjine);


                        if (companyjine < lqjine)//公司余额不足
                        {
                            mainsql.closesql();
                            return false;
                        }



                        companyjine = companyjine - lqjine;



                        sqlcmd = string.Format("UPDATE {0} SET " +
                        " zf_companyrealtimebalance='{1}',zf_status='支付成功',zf_chnumber='{2}' " +
                        " WHERE zf_qgnumber = '{3}' ;",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"),
                        companyjine.ToString("0.00"), chnumber, qgnumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set shop_balance='{1}'  where shop_id='{2}' ",
                            S_SHOP, companyjine.ToString("0.00"), companyaccount);
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        mainsql.closesql();
                        tsall1.Complete();
                    }
                }
                else
                {
                    mysqlcli mainsql = new mysqlcli();
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("UPDATE {0} SET zf_status='支付失败',zf_default='{1}' " +
                    " WHERE zf_qgnumber = '{2}' ;",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), remark, qgnumber);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        logJieKou.Info("零钱回调错误：" + sqlcmd);
                        mainsql.closesql();
                        return false;
                    }
                    mainsql.closesql();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("零钱回调错误：" + ex.Message);
            }
            return true;
        }

        //修理厂零钱回调
        public bool lqxlc_tixianhuidiao(Dictionary<string, string> mapargs)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string qgnumber = mapargs["qgnumber"];
                string chnumber = mapargs["chnumber"];
                string zhifustatus = mapargs["zhifustatus"];
                string remark = mapargs["remark"];
                if (zhifustatus == "支付成功")
                {
                    using (TransactionScope tsall1 = new TransactionScope())
                    {
                        mysqlcli mainsql = new mysqlcli();
                        mainsql.openYongHuServicesql();
                        string datestr = DateTime.Now.ToString("yyyyMM");
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'  ",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgnumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            logJieKou.Info("修理厂回调错误：" + sqlcmd);
                            ds.Dispose();
                            return false;
                        }
                        string companyaccount = ds.Rows[0]["zf_companyaccount"].ToString();

                        string jine = ds.Rows[0]["zf_companyamount"].ToString();
                        //获取余额

                        ds = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} WHERE user_id='{1}'", BIAOUSERCOMPANY, companyaccount));
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            logJieKou.Info("修理厂回调错误：" + sqlcmd);
                            return false;
                        }
                        double comjine = 0;
                        comjine = ds.Rows[0]["user_price"].ToDouble();



                        double lqjine = 0;       //用户的金额                                                                                


                        double.TryParse(jine, out lqjine);

                        if (comjine < lqjine)//公司余额不足
                        {
                            logJieKou.Info("修理厂回调错误：余额不足");
                            mainsql.closesql();
                            return false;
                        }



                        comjine = comjine - lqjine;



                        sqlcmd = string.Format("UPDATE {0} SET " +
                        " zf_companyrealtimebalance='{1}',zf_status='支付成功',zf_chnumber='{2}' " +
                        " WHERE zf_qgnumber = '{3}' ;",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"),
                        comjine.ToString("0.00"), chnumber, qgnumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set user_price='{1}'  where user_id='{2}' ",
                            BIAOUSERCOMPANY, comjine.ToString("0.00"), companyaccount);
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        mainsql.closesql();
                        tsall1.Complete();
                    }
                }
                else
                {
                    mysqlcli mainsql = new mysqlcli();
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("UPDATE {0} SET zf_status='支付失败',zf_default='{1}' " +
                    " WHERE zf_qgnumber = '{2}' ;",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), remark, qgnumber);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        logJieKou.Info("零钱回调错误：" + sqlcmd);
                        mainsql.closesql();
                        return false;
                    }
                    mainsql.closesql();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("零钱回调错误：" + ex.Message);
            }
            return true;
        }

        //用户零钱回调
        public bool lqyh_tixianhuidiao(Dictionary<string, string> mapargs)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            try
            {
                string qgnumber = mapargs["qgnumber"];
                string chnumber = mapargs["chnumber"];
                string zhifustatus = mapargs["zhifustatus"];
                string remark = mapargs["remark"];
                if (zhifustatus == "支付成功")
                {
                    using (TransactionScope tsall1 = new TransactionScope())
                    {
                        mysqlcli mainsql = new mysqlcli();
                        mainsql.openYongHuServicesql();
                        string datestr = DateTime.Now.ToString("yyyyMM");
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}'  ",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgnumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            logJieKou.Info("用户零钱回调错误：" + sqlcmd);
                            ds.Dispose();
                            return false;
                        }
                        string zf_zfonlyid = ds.Rows[0]["zf_zfonlyid"].ToString();

                        string jine = ds.Rows[0]["zf_yhamount"].ToString();
                        //获取余额

                        ds = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} WHERE user_onlyid='{1}'", BIAOYONGHUUSER, zf_zfonlyid));
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            logJieKou.Info("用户零钱回调错误：" + sqlcmd);
                            return false;
                        }
                        double comjine = 0, comoldjine = 0;
                        comoldjine = comjine = ds.Rows[0]["user_balance"].ToDouble();



                        double lqjine = 0;       //用户的金额                                                                                


                        double.TryParse(jine, out lqjine);

                        if (comjine < lqjine)//公司余额不足
                        {
                            logJieKou.Info("用户回调错误：余额不足");
                            mainsql.closesql();
                            return false;
                        }



                        comjine = comjine - lqjine;



                        sqlcmd = string.Format("UPDATE {0} SET " +
                        " zf_companyrealtimebalance='{1}',zf_yholdamount='{2}',zf_status='支付成功',zf_chnumber='{3}' " +
                        " WHERE zf_qgnumber = '{4}' ;",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"),
                        comjine.ToString("0.00"), comoldjine.ToString("0.00"), chnumber, qgnumber);

                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("用户零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        sqlcmd = string.Format("update {0} set user_balance='{1}'  where user_onlyid='{2}' ",
                            BIAOYONGHUUSER, comjine.ToString("0.00"), zf_zfonlyid);
                        sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            logJieKou.Info("用户零钱回调错误：" + sqlcmd);
                            mainsql.closesql();
                            return false;
                        }

                        mainsql.closesql();
                        tsall1.Complete();
                    }
                }
                else
                {
                    mysqlcli mainsql = new mysqlcli();
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("UPDATE {0} SET zf_status='支付失败',zf_default='{1}' " +
                    " WHERE zf_qgnumber = '{2}' ;",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), remark, qgnumber);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        logJieKou.Info("零钱回调错误：" + sqlcmd);
                        mainsql.closesql();
                        return false;
                    }
                    mainsql.closesql();
                }
            }
            catch (Exception ex)
            {
                logJieKou.Info("零钱回调错误：" + ex.Message);
            }
            return true;
        }

        //商品支付成功
        private void shop_huidiao(string orderid, string qgliushuinumber, bool isTrue)
        {
            mysqlcli mainsql = new mysqlcli();

            using (TransactionScope tsall = new TransactionScope())
            {
                #region 修改账单记录表

                mainsql.openYongHuServicesql();

                Dictionary<string, string> mapargs = new Dictionary<string, string>();

                if (CheckZhiFuSHDDBiao(mainsql, orderid, ref mapargs) == false)
                {
                    mainsql.closesql();
                    throw new Exception("该公司并未开通相关功能");  //参数错误
                }
                string shop_lock_balance = mapargs["shop_lock_balance"];       //对应公司的锁定的余额
                string shop_id = mapargs["shop_id"];       //对应公司的余额

                string biaodate = qgliushuinumber.Substring(5, 6);
                string sqlcmd = string.Format("SELECT * from {0} where zf_qgnumber='{1}' AND  zf_companyaccount='{2}' ;",
                    BIAOQGZHIFURECORD + biaodate, qgliushuinumber, shop_id);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count != 1)
                {
                    mainsql.closesql();
                    throw new Exception("没有相应的流水");                                          //参数错误
                }
                if (!isTrue)
                {
                    sqlcmd = string.Format("update {0} set zf_status='支付失败' where zf_qgnumber='{1}' ",
                       BIAOQGZHIFURECORD + biaodate, qgliushuinumber);
                    mainsql.SqlExcuteNoReturn(sqlcmd);
                    return;
                }
                if (ds.Rows[0]["zf_status"].ToString() == "支付成功")
                {
                    return;
                }


                string zf_companyamount = ds.Rows[0]["zf_companyamount"].ToString();


                double companyamount = 0;
                double.TryParse(zf_companyamount, out companyamount);//对应公司的金额

                double dbcompanyrealtimebalance = 0;

                double.TryParse(shop_lock_balance, out dbcompanyrealtimebalance);//公司得到的金额



                dbcompanyrealtimebalance += companyamount;
                sqlcmd = string.Format("update {0} set zf_status='支付成功',zf_qgrealtimebalance='{1}',zf_companyrealtimebalance='{2}'  where zf_qgnumber='{3}' ",
                   BIAOQGZHIFURECORD + biaodate, 0.ToString("0.00"), dbcompanyrealtimebalance.ToString("0.00"), qgliushuinumber);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                if (sqlret != 1)
                {
                    mainsql.closesql();
                    throw new Exception("修改支付记录失败");  //参数错误
                }

                if (string.IsNullOrWhiteSpace(mapargs["order_pay_liushui"]))
                {
                    sqlcmd = string.Format("update {0} set shop_lock_balance='{1}'  where shop_id='{2}' ",
                     S_SHOP, dbcompanyrealtimebalance.ToString("0.00"), shop_id);
                    sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        throw new Exception("修改公司账目失败");  //参数错误
                    }
                }
                sqlcmd = string.Format("update {0} set order_pay_status='2',order_status='1'  where order_id='{1}' ",
                S_ORDER, orderid);
                sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                if (sqlret != 1)
                {
                    mainsql.closesql();
                    throw new Exception("修改订单付款状态");  //参数错误
                }

                #region 发微信消息
                var phone = mapargs["user_phone"];
                var name = mapargs["user_name"];
                var price = mapargs["order_price"].ToDouble();
                var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shop_id}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();
                foreach (var item in users)
                {
                    var openid = item["user_openid_juhesheng"];

                    if (!string.IsNullOrWhiteSpace(openid))
                    {
                        //发送消息
                        WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.ZhifuMsg()
                        {
                            miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                            {
                                pagepath = "/pages/my/store/store?ShopId=" + mapargs["shop_id"]
                            },
                            touser = openid,
                            data = new WebServiceShopping.wechartTools.ZhifuMsg.DataModel()
                            {
                                keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = name + "(" + phone + ")"
                                },
                                keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                },
                                keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = "线上支付"
                                },
                                keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = price.ToString("C") + "元"
                                }
                            }
                        });
                    }
                }
                #endregion

                mainsql.closesql();
                tsall.Complete();
                #endregion
            }
        }

        //维修支付成功
        private void weixiu_huidiao(string repair_id, string qgliushuinumber, bool isTrue)
        {
            mysqlcli mainsql = new mysqlcli();

            using (TransactionScope tsall = new TransactionScope())
            {


                mainsql.openYongHuServicesql();
                string status3 = "0";
                string zf_status = "支付失败";


            

                string sqlcmd = string.Format("select * from {0} WHERE repair_id ='{1}' AND   repair_status1='3' AND repair_status2='5'  AND repair_status3='0'  ;",
                    BIAOUSERREPAIR, repair_id);
                var ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    return;
                }

                if (isTrue == true)
                {
                    status3 = "1";
                    zf_status = "支付成功";
                    string repair_couponid = ds.Rows[0]["repair_couponid"].ToString();


                    if (repair_couponid != "")
                    {
                        var sql = $"update s_coupon set coupon_status=1,coupon_updateime=NOW() where Sid='{repair_couponid}';";
                        mainsql.SqlExcuteNoReturn(sql);
                    }
                }


                string updatestr = string.Format(" repair_status1='3',repair_status2='5' ,repair_status3='{0}' ", status3);
                string cmd = string.Format(" update {0} set {1} where repair_id ='{2}' ;", BIAOUSERREPAIR, updatestr, repair_id);
                int retint = mainsql.SqlExcuteNoReturn(cmd);
                if (retint != 1)
                {
                    mainsql.closesql();
                    throw new Exception("用户更改状态失败");
                }
                string biaodate = qgliushuinumber.Substring(5, 6);
                sqlcmd = string.Format("update {0} set zf_status='{1}'  where zf_qgnumber='{2}' ",
                 BIAOQGZHIFURECORD + biaodate, zf_status, qgliushuinumber);
                int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                if (sqlret != 1)
                {
                    mainsql.closesql();
                    return;
                }
                mainsql.closesql();
                tsall.Complete();

            }
        }

        //团购支付成功
        private void tuangou_huidiao(string orders, string qgliushuinumber, bool isTrue, ILog logJieKou)
        {
            mysqlcli mainsql = new mysqlcli();
            try
            {

                mainsql.openYongHuServicesql();

                using (MySqlTransaction tr = mainsql.Connection().BeginTransaction())
                {
                    string status3 = "5";
                    string zf_status = "支付失败";
                    var orderArr = orders.Trim(',').Split(',');

                    if (isTrue)
                    {
                        status3 = "1";
                        zf_status = "支付成功";
                    }

                    for (int i = 0; i < orderArr.Length; i++)
                    {
                        //查询订单未支付订单
                        var orderId = orderArr[i].ToString();
                        var sql = $@"select * from s_commoditybuyorder where (buy_order_pay_status=0 || buy_order_pay_status=5) and buy_order_id='{orderId}'";
                        var ds = mainsql.SqlExcuteWithReturn(sql);

                        if (ds.Rows.Count == 0)
                        {
                            continue;
                        }

                        var userId = ds.Rows[0]["user_id"].ToString();
                        var commodityId = ds.Rows[0]["commodity_id"].ToString();

                        if (!string.IsNullOrWhiteSpace(ds.Rows[0]["buy_order_yhq"].ToString()))
                        {

                            if (isTrue)
                            {
                                //修改订单未支付订单状态
                                sql = $"update s_coupon set coupon_status=1,coupon_updateime=NOW()  where Sid='{ds.Rows[0]["buy_order_yhq"]}';";

                                mainsql.SqlExcuteNoReturn(sql, tr);
                            }
                        }

                        //删除购物车中的产品
                        sql = $"Delete from {BIAOBUYERCOLLPRODUCT} where user_id='{userId}' and  prd_id='{commodityId}'";
                        logJieKou.Info(">>>" + sql);
                        mainsql.SqlExcuteNoReturn(sql, tr);

                        var companyId = ds.Rows[0]["company_id"].ToString();
                        var price = ds.Rows[0]["buy_order_price"].ToString();//订单金额

                        //修改订单未支付订单状态
                        sql = $"update s_commoditybuyorder set buy_order_pay_status={status3},buy_order_pay_time=NOW() where buy_order_id='{orderId}';";
                        logJieKou.Info(">>>" + sql);
                        mainsql.SqlExcuteNoReturn(sql, tr);

                        //修改流水支付状态
                        string biaodate = qgliushuinumber.Substring(5, 6);
                        sql = string.Format("update {0} set zf_status='{1}' where zf_biaoid='{2}' ",
                         BIAOQGZHIFURECORD + biaodate, zf_status, orderId);

                        logJieKou.Info(sql + ":" + zf_status + ":" + orderId);
                        mainsql.SqlExcuteNoReturn(sql, tr);
                        logJieKou.Info(qgliushuinumber + ":" + orderId);

                    }

                    tr.Commit();
                    mainsql.closesql();

                }
            }
            catch (Exception e)
            {
                logJieKou.Info(e.Message);
            }
        }

        #endregion

        //请求传化 后置分账
        [WebMethod(Description = "请求传化 后置分账")]
        public string xcx_tomultipay_fenzhang(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            logJieKou.Info("传化支付后置分账-" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            try
            {

                string orderid = comrcv.Map_Args["orderid"];            //订单号

                using (TransactionScope tsall = new TransactionScope())
                {
                    #region 修改账单记录表

                    mainsql.openYongHuServicesql();

                    Dictionary<string, string> mapargs = new Dictionary<string, string>();

                    if (CheckZhiFuSHDDBiao(mainsql, orderid, ref mapargs) == false)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "该公司并未开通相关功能";  //参数错误
                        goto EXIT;
                    }
                    string shop_id = mapargs["shop_id"];
                    string paytime = mapargs["order_pay_time"];

                    paytime = "2020-11-01";
                    /**
                     * 查询订单支付时间，店铺ID
                     * 通过支付时间、店铺ID、订单ID 查询支付记录，返回支付成功的流水号。如果没有！ 报异常
                     * 通过流水号调用传化分账接口
                     * 
                     * */


                    string biaodate = paytime.ToDateTime().Value.ToString("yyyyMM");
                    string sqlcmd = string.Format("SELECT * from {0} where zf_status='支付成功' AND  zf_companyaccount='{1}' AND zf_biaoid='{2}' ;",
                        BIAOQGZHIFURECORD + biaodate, shop_id, orderid);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "没有相应的流水";                                          //参数错误
                        goto EXIT;
                    }
                    var qgliushuinumber = ds.Rows[0]["zf_qgnumber"].ToString();
                    if (string.IsNullOrWhiteSpace(qgliushuinumber))
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "支付流水号为空";                                          //参数错误
                        goto EXIT;
                    }

                    #region 计算分账金额
                    var jine = mapargs["order_price"];
                    var comfeilvstr = mapargs["shop_rate"];
                    if (string.IsNullOrWhiteSpace(comfeilvstr))
                    {
                        comfeilvstr = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
                    }

                    //计算相关金额
                    double yonghujine = 0;   //支付的金额
                    double companyjine = 0;   //公司得到的金额

                    double comfeilvdb = 0;   //青贯跟公司费率


                    double.TryParse(jine, out yonghujine);
                    double.TryParse(comfeilvstr, out comfeilvdb);


                    if (yonghujine == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "金额错误";  //参数错误
                        goto EXIT;
                    }

                    double companyjineshouxu = yonghujine * comfeilvdb;
                    companyjine = yonghujine;
                    if (comfeilvdb > 0)
                    {
                        var companyjineshouxu2 = Math.Round(companyjineshouxu, 2);//将手续费变成两位小数
                        if (companyjineshouxu2 < 0.01)
                            companyjineshouxu2 = 0.01;
                        if (companyjineshouxu2 < companyjineshouxu)
                            companyjineshouxu2 += 0.01;
                        if (yonghujine <= companyjineshouxu2)
                        {
                            companyjineshouxu2 = 0;
                        }
                        companyjineshouxu = Math.Round(companyjineshouxu2, 2);

                        companyjine = yonghujine - companyjineshouxu;
                        companyjine = Math.Round(companyjine, 2);
                    }
                    #endregion
                    var chaccount = mainsql.SqlExecuteScalar("select c_account from s_shopchuanhua where c_id='10000000000'")?.ToString();
                    mapargs.Add("qgliushuinumber", qgliushuinumber);
                    mapargs.Add("shareinfo", $"{mapargs["ch_account"]},{companyjine};{chaccount},{companyjineshouxu}");

                    if (!CH_ZHIFU_Share(ref mapargs))
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "请求分账传化服务器异常";
                        goto EXIT;
                    }

                    mainsql.closesql();
                    tsall.Complete();

                    #endregion
                }
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                logJieKou.Info("传化支付后置分账异常-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //请求传化支付商品订单费用
        [WebMethod(Description = "正式版本")]
        public string xcx_tomultipay_spzhifu(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            string qgliushuinumber = "";
            try
            {
                logJieKou.Info("请求传化支付商品订单费用开始请求-");
                string shop_id = "";                                  //商户基本id
                string openid = comrcv.Map_Args["openid"];              //当前支付人的OPENID
                string jine = comrcv.Map_Args["cost"];                  //金额
                string orderid = comrcv.Map_Args["orderid"];            //订单号
                string user_phone = "";             //买家人电话
                string user_name = "";        //买家人姓名
                string yfonlyid = "";        //买家人唯一编码
                string chbusinessrecordnumber = "";
                string companynumber = "";
                string shop_name = "";
                string comfeilvstr = "";
                string qgnumberdate = "";
                string qgnumber = "";
                string oldcost = jine;//原金额


                using (TransactionScope tsall = new TransactionScope())
                {
                    mainsql.openYongHuServicesql();

                    #region 查支付公司表的信息
                    Dictionary<string, string> mapargs = new Dictionary<string, string>();

                    if (CheckZhiFuSHDDBiao(mainsql, orderid, ref mapargs) == false)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "该商户并未开通相关功能";  //参数错误
                        goto EXIT;
                    }
                    shop_name = mapargs["shop_name"];
                    comfeilvstr = mapargs["shop_rate"];
                    if (string.IsNullOrWhiteSpace(comfeilvstr))
                    {
                        comfeilvstr = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
                    }
                    shop_id = mapargs["shop_id"];

                    user_phone = mapargs["user_phone"];
                    user_name = mapargs["user_name"];
                    yfonlyid = mapargs["order_to_user_id"];
                    qgnumberdate = mapargs["qgnumberdate"];
                    qgnumber = mapargs["qgnumber"];



                    qgliushuinumber = GetCompanyDDNumber(mainsql, qgnumberdate, "qingguan");
                    //生成青贯流水号
                    qgliushuinumber = qgnumber + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;


                    #endregion

                    #region 计算分账金额

                    //计算相关金额
                    double yonghujine = 0;   //支付的金额
                    double companyjine = 0;   //公司得到的金额

                    double comfeilvdb = 0;   //青贯跟公司费率


                    double.TryParse(jine, out yonghujine);
                    double.TryParse(comfeilvstr, out comfeilvdb);


                    if (yonghujine == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "金额错误";  //参数错误
                        goto EXIT;
                    }

                    double companyjineshouxu = yonghujine * comfeilvdb;
                    companyjine = yonghujine;
                    if (comfeilvdb > 0)
                    {
                        var companyjineshouxu2 = Math.Round(companyjineshouxu, 2);//将手续费变成两位小数
                        if (companyjineshouxu2 < 0.01)
                            companyjineshouxu2 = 0.01;
                        if (companyjineshouxu2 < companyjineshouxu)
                            companyjineshouxu2 += 0.01;
                        if (yonghujine <= companyjineshouxu2)
                        {
                            companyjineshouxu2 = 0;
                        }
                        companyjineshouxu = Math.Round(companyjineshouxu2, 2);

                        companyjine = yonghujine - companyjineshouxu;
                        companyjine = Math.Round(companyjine, 2);
                    }
                    #endregion

                    #region 调用传化接口

                    string subjectstring = shop_name + "-运费支付";
                    string logip = "";
                    try
                    {
                        logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                    }
                    catch
                    { }

                    Dictionary<string, string> zfmapargs = new Dictionary<string, string>();
                    zfmapargs.Add("subjectstring", subjectstring);
                    zfmapargs.Add("logip", logip);
                    zfmapargs.Add("companyname", shop_name);
                    zfmapargs.Add("qgliushuinumber", qgliushuinumber);
                    zfmapargs.Add("jine", jine);
                    zfmapargs.Add("openid", openid);
                    zfmapargs.Add("ErrorMsg", "无错误");
                    var chaccount = mapargs["ch_account"];
                    logJieKou.Info("分账账号验证：" + chaccount);
                    if (!string.IsNullOrWhiteSpace(chaccount))
                    {
                        //logJieKou.Info("分账模式：" + chaccount + ":" + companyjine + ";" + companyjineshouxu);
                        logJieKou.Info("分账模式：" + qgliushuinumber + "：8800012802019:" + companyjine + ";8800012801977:" + companyjineshouxu);
                        //如果是分账模式
                        zfmapargs.Add("billsubtype", "03");
                        //后置分账，这个参数只能为空
                        zfmapargs.Add("shareinfo", "");

                        //zfmapargs.Add("shareinfo", $"8800012802019,{companyjine};8800012801977,{companyjineshouxu}");
                        if (mainsql.SqlExcuteNoReturn($"update {S_ORDER} set order_pay_liushui='{qgliushuinumber}',order_pay_status='1' where order_id='{orderid}'") != 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改记录失败";
                            goto EXIT;
                        }
                    }
                    else
                    {
                        if (mainsql.SqlExcuteNoReturn($"update {S_ORDER} set order_pay_status='1' where order_id='{orderid}'") != 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改记录失败";
                            goto EXIT;
                        }
                    }
                    if (CH_ZHIFU_COMMON(ref zfmapargs) == true)
                    {
                        ret.Map_Args["appId"] = zfmapargs["appId"];
                        ret.Map_Args["timeStamp"] = zfmapargs["timeStamp"];
                        ret.Map_Args["nonceStr"] = zfmapargs["nonceStr"];
                        ret.Map_Args["package"] = zfmapargs["package"];
                        ret.Map_Args["signType"] = zfmapargs["signType"];
                        ret.Map_Args["paySign"] = zfmapargs["paySign"];
                        ret.Map_Args["qgliushuinumber"] = qgliushuinumber;
                        chbusinessrecordnumber = zfmapargs["chbusinessrecordnumber"];
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = zfmapargs["ErrorMsg"];   //参数错误
                        goto EXIT;
                    }
                    #endregion

                    #region 生成账单记录表

                    string defaultstr = string.Format("用户支付{0}元,实际到账{1}元", oldcost, companyjine.ToString("0.00"));


                    string sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                        "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                        " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','微信','2','1','{16}')",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "商品支付", "等待支付", qgliushuinumber,
                        chbusinessrecordnumber, orderid, shop_id, companynumber, shop_name,
                        yonghujine.ToString("0.00"), oldcost, 0.ToString("0.00"), companyjine.ToString("0.00"), defaultstr, user_phone, yfonlyid);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "插入记录失败";  //参数错误
                        goto EXIT;
                    }
                    #endregion

                    mainsql.closesql();
                    tsall.Complete();
                }


            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //传化支付商品订单费用成功
        [WebMethod(Description = "正式版本")]
        public string xcx_tomultipay_spzhifuOk(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);

            try
            {
                string qgliushuinumber = comrcv.Map_Args["qgliushuinumber"];
                string orderid = comrcv.Map_Args["orderid"];            //订单号

                shop_huidiao(orderid, qgliushuinumber, true);
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                logJieKou.Info("传化支付商品订单费用异常-" + ex.Message);
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //请求传化支付商品订单费用失败
        [WebMethod(Description = "正式版本")]
        public string xcx_tomultipay_spzhifuCancel(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();

            try
            {

                string qgliushuinumber = comrcv.Map_Args["qgliushuinumber"];

                using (TransactionScope tsall = new TransactionScope())
                {

                    #region 修改账单记录表

                    mainsql.openYongHuServicesql();

                    string biaodate = qgliushuinumber.Substring(5, 6);
                    string sqlcmd = string.Format("SELECT * from {0} where zf_qgnumber='{1}' AND zf_status='等待支付' ;",
                        BIAOQGZHIFURECORD + biaodate, qgliushuinumber);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "没有相应的流水";                                          //参数错误
                        goto EXIT;
                    }


                    sqlcmd = string.Format("update {0} set zf_status='支付失败'  where zf_qgnumber='{1}' ",
                       BIAOQGZHIFURECORD + biaodate, qgliushuinumber);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改支付记录失败";  //参数错误
                        goto EXIT;
                    }

                    mainsql.closesql();
                    tsall.Complete();

                    #endregion
                }
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                logJieKou.Info("请求传化支付商品订单费用失败-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //商户请求零钱提现
        [WebMethod(Description = "正式版本")]
        public string xcx_shasktixian_lq(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            string qgliushuinumber = "";
            try
            {
                logJieKou.Info("商户请求零钱提现-");
                string shop_id = comrcv.Map_Args["shop_id"];    //商户ID
                string jine = comrcv.Map_Args["cost"];          //金额             
                string openid = comrcv.Map_Args["openid"];      //openid
                string yhphone = comrcv.Map_Args["yhphone"];    //用户电话
                string yhonlyid = comrcv.Map_Args["yhonlyid"];  //用户唯一ID
                string bankname = comrcv.Map_Args["bankname"];  //银行名称
                string username = comrcv.Map_Args["username"];  //户名
                string bankcardid = comrcv.Map_Args["bankcardid"];  //卡号
                string chbusinessrecordnumber = "";

                string shop_name = "";
                string qgnumberdate = "";
                string qgnumber = "";

                string shop_balance = "";
                using (TransactionScope tsall1 = new TransactionScope())
                {
                    #region 查支付公司表的信息

                    mainsql.openYongHuServicesql();

                    Dictionary<string, string> mapargs = new Dictionary<string, string>();

                    if (CheckZhiFuSHIDBiao(mainsql, shop_id, ref mapargs) == false)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "该商户并未开通相关功能";  //参数错误
                        goto EXIT;
                    }

                    shop_balance = mapargs["shop_balance"];       //对应公司的余额
                    shop_name = mapargs["shop_name"];
                    qgnumberdate = mapargs["qgnumberdate"];
                    qgnumber = mapargs["qgnumber"];

                    qgliushuinumber = GetCompanyDDNumber(mainsql, qgnumberdate, "qingguan");
                    //生成青贯流水号
                    qgliushuinumber = qgnumber + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;



                    #endregion

                    #region 计算和插入表

                    double txjine = 0;
                    double shjine = 0;
                    double.TryParse(jine, out txjine);
                    double.TryParse(shop_balance, out shjine);


                    if (shjine < txjine)
                    {
                        ret.Map_Args["ErrorMsg"] = "商户余额不足";
                        goto EXIT;
                    }

                    string zf_default = string.Format("商户{0}零钱提现到{1}的卡上", shop_name, username);
                    //生成账单记录表


                    string sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_companyaccount," +
                    "zf_companynumber,zf_companyname,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                    " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','零钱','0','2','{12}')",
                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "商户零钱提现", "等待支付", qgliushuinumber,
                    chbusinessrecordnumber, shop_id, "", shop_name, txjine.ToString("0.00"), zf_default, yhphone, yhonlyid);

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "插入记录失败";
                        goto EXIT;
                    }
                    mainsql.closesql();
                    tsall1.Complete();
                    #endregion
                }

                #region 调用传化接口

                string subjectstring = shop_name + "-商户提现";
                string qgppid = QGZHIFUQGAPPID;
                string chappid = QGZHIFUCHAPPID;
                string sk = QGZHIFUCHSK;
                string com_accountnumber = QGZHIFUACCOUNTNUMBER;

                string logip = "";
                try
                {
                    logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                }
                catch
                { }
                String service_id = "tf56enterprise.enterprise.payForCustomer";
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                paramMap.Add("appid", chappid);
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                paramMap.Add("service_id", service_id);
                paramMap.Add("sign_type", "RSA");
                paramMap.Add("businessnumber", qgliushuinumber);
                paramMap.Add("subject", "商户提现");
                paramMap.Add("transactionamount", jine);
                paramMap.Add("bankcardnumber", bankcardid);
                paramMap.Add("bankcardname", username);
                paramMap.Add("bankname", bankname);
                paramMap.Add("bankcardtype", "个人");
                paramMap.Add("bankaccounttype", "储蓄卡");
                paramMap.Add("backurl", XCXBACKURL);
                paramMap.Add("fromaccountnumber", com_accountnumber);
                paramMap.Add("terminal", "Android");
                string tf_sign = signForm(paramMap, sk);
                paramMap.Add("tf_sign", tf_sign);
                paramMap.Remove("dog_sk");
                string retsult = PostWebRequestForm(baseurl, paramMap);
                JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                logJieKou.Info("结果数据：\n" + retsultJson.ToString());
                string coderel = retsultJson["code"].ToString();
                string result = retsultJson["result"].ToString();
                string cuomsg = retsultJson["msg"].ToString();
                string retdata = retsultJson["data"].ToString();
                ret.Map_Args["ErrorMsg"] = cuomsg;
                logJieKou.Info("结果数据：\n" + result.ToString());
                if (result.Equals("success"))
                {
                    JObject alldataJson = JsonConvert.DeserializeObject(retdata) as JObject;
                    chbusinessrecordnumber = alldataJson["businessrecordnumber"].ToString();
                    //定时查询支付状态  
                    int count = CHAXUNTIME;
                    int interval = 1000;
                    ret.Map_Args["ErrorMsg"] = "处理中";
                    mainsql.openYongHuServicesql();
                    for (int i = 1; i <= count; i++)
                    {
                        string sqlcmd = string.Format("select * from {0} where zf_qgnumber = '{1}' ;",
                            BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), qgliushuinumber);
                        DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            ret.Map_Args["ErrorMsg"] = "没有流水记录";
                            goto EXIT;
                        }

                        string zf_status = ds.Rows[0]["zf_status"].ToString();
                        if (zf_status.Equals("支付成功"))
                        {
                            ret.Byte_Flag = (sbyte)1;
                            mainsql.closesql();
                            ds.Dispose();
                            goto EXIT;
                        }
                        else if (zf_status.Equals("支付失败"))
                        {
                            mainsql.closesql();
                            ds.Dispose();
                            ret.Map_Args["ErrorMsg"] = ds.Rows[0]["zf_default"].ToString();
                            goto EXIT;
                        }
                        Thread.Sleep(interval);
                    }
                    mainsql.closesql();

                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = "商户请求零钱提现-" + cuomsg;  //参数错误
                    goto EXIT;
                }

                #endregion

            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = "商户请求零钱提现-" + ex.Message;  //参数错误
                logJieKou.Info("商户请求零钱提现-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //商户获取商户账单
        [WebMethod(Description = "正式版本")]
        public string xcx_shgetzd(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();

            try
            {
                string shop_id = comrcv.Map_Args["shop_id"];
                string biaodate = comrcv.Map_Args["biaodate"];
                string pageindex = comrcv.Map_Args["pageindex"];

                mainsql.openYongHuServicesql();
                Dictionary<string, string> mapargs = new Dictionary<string, string>();

                if (CheckZhiFuSHIDBiao(mainsql, shop_id, ref mapargs) == false)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "该商户并未开通相关功能";  //参数错误
                    goto EXIT;
                }


                string shop_name = mapargs["shop_name"];


                logJieKou.Info("商户获取商户账单-" + shop_name);
                int pagecount = 100;
                int intpageindex = 0;
                int.TryParse(pageindex, out intpageindex);
                intpageindex = intpageindex * pagecount;
                string limitstring = string.Format("limit {0},{1} ", intpageindex, pagecount);


                string sqlcmd = string.Format("SELECT * FROM {0}" +
                    " where zf_status ='支付成功' AND zf_companyaccount='{1}' AND zf_comshouzhi <> '0' ORDER BY zf_time DESC {2} ;",
                    BIAOQGZHIFURECORD + biaodate, shop_id, limitstring);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                ds.Dispose();
            }
            catch (Exception ex)
            {
                logJieKou.Info("商户获取商户账单-" + ex.Message);
                mainsql.closesql();

                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //商户请求退款
        [WebMethod(Description = "正式版本")]
        public string xcx_refund(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            logJieKou.Info(msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    byte[] bytrcv = Convert.FromBase64String(msg);
                    ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                    mainsql.openShopServicesql();

                    //查找订单
                    var buy_order_id = comrcv.Map_Args["buyOrderId"];//商品订单ID
                    var sql = $@"select * from s_commoditybuyorder where buy_order_pay_status=2 and buy_order_id='{buy_order_id}'";//2
                    var order = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                    if (order == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单未申请退款";  //参数错误
                        mainsql.closesql();
                        goto EXIT;
                    }

                    var companyId = order["company_id"];//门店ID
                    var tableName = $"{BIAOQGZHIFURECORD}{DateTime.Parse(order["buy_order_pay_time"].ToString()).ToString("yyyyMM")}";//查找流水
                    sql = $"select * from {tableName} where zf_biaoid='{buy_order_id}' and zf_qgnumber<>'' and zf_qgnumber is not null order by zf_time desc limit 0,1";
                    var qgzhifurecord = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                    if (qgzhifurecord == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "未找到支付流水";  //参数错误
                        mainsql.closesql();
                        goto EXIT;
                    }

                    var qgliushuinumber = qgzhifurecord["zf_qgnumber"];//订单流水号
                    var refundbusinessnumber = GetLdpLiushui(mainsql);
                    var logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                    var chappid = QGZHIFUCHAPPID;
                    var sk = QGZHIFUCHSK;
                    var com_accountnumber = QGZHIFUACCOUNTNUMBER;
                    var service_id = "tf56pay.gateway.orderRefund";
                    //公共参数
                    var paramMap = new Dictionary<string, object>();
                    paramMap.Add("appid", chappid);
                    paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                    paramMap.Add("service_id", service_id);
                    paramMap.Add("sign_type", "RSA");
                    paramMap.Add("terminal", "PC");
                    paramMap.Add("backurl", RefundBackurl);
                    paramMap.Add("businessnumber", qgliushuinumber);
                    paramMap.Add("refundbusinessnumber", refundbusinessnumber);

                    if (!string.IsNullOrWhiteSpace(order["buy_order_yhq"]))
                    {
                        paramMap.Add("refundamount", order["buy_order_pay_price"]);
                    }
                    else
                    {
                        paramMap.Add("refundamount", order["buy_order_price"]);
                    }

                    paramMap.Add("clientip", logip);
                    string tf_sign = signForm(paramMap, sk);
                    paramMap.Add("tf_sign", tf_sign);

                    string jsonStr = JsonConvert.SerializeObject(paramMap);
                    string retsult = PostWebRequestForm(baseurl, paramMap);
                    logJieKou.Info("聚合支付-" + companyId + "-传化接口返回-" + retsult);
                    JObject retsultJson = JsonConvert.DeserializeObject(retsult) as JObject;
                    string coderel = retsultJson["code"].ToString();
                    string biz_code = retsultJson["biz_code"].ToString();
                    string biz_msg = retsultJson["biz_msg"].ToString();

                    if (coderel.Equals("GP_00") && biz_code.Equals("GPBIZ_00"))
                    {
                        string alldata = retsultJson["data"].ToString();
                        JObject data = JsonConvert.DeserializeObject(alldata) as JObject;
                        var chrefundnumber = data["refundbusinessrecordnumber"].ToString();

                        //修改订单未支付订单状态
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@orderId", buy_order_id));
                        sql = "update s_commoditybuyorder set buy_order_pay_status=3,buy_order_update_time=NOW() where buy_order_id=@orderId;";

                        var num = mainsql.SqlExcuteNoReturn(sql, paras.ToArray());

                        if (num < 1)
                        {
                            ret.Map_Args["ErrorOrderMsg"] = "订单更改状态失败";
                            logJieKou.Info("订单更改状态失败：" + sql);
                        }

                        var sqlCmd = $"show columns from {tableName} like 'zf_qgrefundnumber'";
                        DataTable colTable = mainsql.SqlExcuteWithReturn(sqlCmd);
                        if (colTable.Rows.Count == 0)
                        {
                            sqlCmd = $"alter table {tableName} add zf_qgrefundnumber varchar(100);";
                            var num3 = mainsql.SqlExcuteNoReturn(sqlCmd);
                        }

                        sqlCmd = $"show columns from {tableName} like 'zf_chrefundnumber'";
                        colTable = mainsql.SqlExcuteWithReturn(sqlCmd);
                        if (colTable.Rows.Count == 0)
                        {
                            sqlCmd = $"alter table {tableName} add zf_chrefundnumber varchar(100);";
                            var num3 = mainsql.SqlExcuteNoReturn(sqlCmd);
                        }

                        sql = string.Format("update {0} set zf_status='{1}',zf_qgrefundnumber='{3}',zf_chrefundnumber='{4}' where zf_biaoid='{2}' ",
                        tableName, "等待退款", buy_order_id, refundbusinessnumber, chrefundnumber);
                        int sqlret = mainsql.SqlExcuteNoReturn(sql);

                        if (sqlret != 1)
                        {
                            ret.Map_Args["ErrorMsg"] = "流水状态更改错误";
                            logJieKou.Info("流水状态更改错误：" + sql);
                        }
                        else
                        {
                            ret.Byte_Flag = (sbyte)1;
                            ret.Map_Args["ErrorMsg"] = "操作成功";  //参数错误
                        }
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = "聚合支付返回错误信息" + biz_msg;
                        logJieKou.Info("聚合支付返回错误信息" + biz_msg);
                    }

                    mainsql.closesql();
                    tsall.Complete();

                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "退款发生错误 - " + ex.Message;  //参数错误
                logJieKou.Info("退款发生错误-" + ex.Message);
            }

            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        /*
        //商户查代收状态
        [WebMethod(Description = "基础调用")]
        public string xcx_shcheckdaishou(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }

                string biaoids = comrcv.Map_Args["biaoids"];
                string companyaccount = comrcv.Map_Args["companyaccount"];
                logJieKou.Info("商户查代收状态-" + biaoids);

                string[] biaoidarr = biaoids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string inbiaoidsstr = "'" + string.Join("','", biaoidarr) + "'";

                mainsql.openRoutingServicesql();
                string sqlcmd = string.Format("SELECT * FROM {0} where UserId = '{1}'", BIAOALLROUTE, companyaccount);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();

                    logJieKou.Info("没有查询到相关数据-" + sqlcmd);
                    ret.Map_Args["ErrorMsg"] = "没有查询到相关数据";  //参数错误
                    goto EXIT;
                }
                mainsql.closesql();
                SqlInfo SqlInfo1 = new SqlInfo();
                SqlInfo1.String_sqlip = ds.Rows[0]["ReadDbAddr"].ToString();
                SqlInfo1.String_sqlname = ds.Rows[0]["ReadDbName"].ToString();
                SqlInfo1.String_sqluser = ds.Rows[0]["ReadDbUser"].ToString();
                SqlInfo1.String_sqlpwd = ds.Rows[0]["ReadDbPwd"].ToString();
                SqlInfo1.String_sqlport = ds.Rows[0]["ReadDbPort"].ToString();
                mainsql.opensql(SqlInfo1);

                sqlcmd = string.Format("select Password from user where  Account ='{0}' AND Status ='授权';",
                       companyaccount);
                ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    ds.Dispose();
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "没有查询到任何公司信息。";
                    goto EXIT;
                }
                string sqlcanshu = " * ";
                string limitstring = "";
                if (comrcv.Map_Args.Keys.Contains("limitstart") == true)
                {
                    limitstring = string.Format(" limit {0},{1} ", comrcv.Map_Args["limitstart"], comrcv.Map_Args["limitend"]);
                }
                else
                {
                    limitstring = " limit 100 ";
                }

                sqlcmd = string.Format("select {2} from {0} where  Biao_Id IN ({1})  {3} ;",
                        companyaccount + DAISHOUBIAONAME, inbiaoidsstr, sqlcanshu, limitstring);
                ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    ds.Dispose();
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "没有查询到任何代收。";
                    goto EXIT;
                }
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                foreach (DataRow row in ds.Rows)
                {
                    Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                    foreach (DataColumn dl in ds.Columns)
                    {
                        newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                    }
                    ret.List_MapArgs.Add(newNetImple);
                }
                ret.Byte_Flag = 1;
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //商户请求提取代收
        [WebMethod(Description = "正式版本")]
        public string xcx_shaskdaishoutx(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
            mysqlcli mainsql = new mysqlcli();
            mysqlcli zfmainsql = new mysqlcli();
            try
            {
                logJieKou.Info("请求提取代收-");
                string companyaccount = comrcv.Map_Args["companyaccount"];//物流公司的账号
                string allcost = comrcv.Map_Args["allcost"];  //所有代收金额


                string biaoids = comrcv.Map_Args["biaoids"];//运单号逗号隔开
                string biaocount = comrcv.Map_Args["biaocount"];//运单的数量

                string shop_id = comrcv.Map_Args["shop_id"];//商户ID
                string shop_name = comrcv.Map_Args["shop_name"];//商户名
                string order_id = comrcv.Map_Args["order_id"];//订单的id
                string qgliushuinumber = "";
                #region 查物流公司表的信息

                mainsql.openYongHuServicesql();


               string sqlcmd = string.Format("SELECT * from {0} where com_account='{1}'  ;", BIAOQGZHIFUCOMPANY, companyaccount);
               DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "没有查询到该公司相关数据";  //参数错误
                    goto EXIT;
                }


                if (ds.Rows[0]["com_daishouztopen"].ToString() != "1")
                {
                    ret.Map_Args["ErrorMsg"] = "该公司并未开通代收款提现功能";  //参数错误
                    goto EXIT;
                }
                double comamount = 0;
                double dballcost = 0;
                double comfeilvdb = 0;     //公司的比例
                double comminshouxudb = 0; //收最小的手续费
                double.TryParse(allcost, out dballcost);
                double.TryParse(ds.Rows[0]["com_daishouztfeilv"].ToString(), out comfeilvdb);
                double.TryParse(ds.Rows[0]["com_daishouminshouxu"].ToString(), out comminshouxudb);
                double.TryParse(ds.Rows[0]["com_amount"].ToString(), out comamount);
                double daishousshouxu = dballcost * comfeilvdb;
                if (daishousshouxu < comminshouxudb)
                {
                    daishousshouxu = comminshouxudb;
                }
                double realdaishoutx = dballcost - daishousshouxu;
                if (comamount < realdaishoutx)
                {
                    ret.Map_Args["ErrorMsg"] = "该公司余额不足不支持立即提现功能";
                    goto EXIT;
                }

                string companydate = ds.Rows[0]["com_numberdate"].ToString();
                string companynumber = ds.Rows[0]["com_number"].ToString();
                string companyname = ds.Rows[0]["com_name"].ToString();
                qgliushuinumber = GetCompanyDDNumber(mainsql, companydate, companyaccount);
                //生成青贯流水号
                qgliushuinumber = companynumber + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;
                mainsql.closesql();
                #endregion

                #region 查标准路由表里面的公司信息

                SqlInfo SqlInfo1 = new SqlInfo();
                if (CheckRouteComBiao(mainsql, companyaccount, ref SqlInfo1) == false)
                {
                    ret.Map_Args["ErrorMsg"] = "该公司并未开通相关功能";
                    goto EXIT;
                }
                #endregion


                using (TransactionScope tsall1 = new TransactionScope())//进入事件
                {
                    string[] biaoidarr = biaoids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    string inbiaoidsstr = "'" + string.Join("','", biaoidarr) + "'";
                    string intsertkeystr = " ";
                    string intsertvaluestr = " ";
                    int sqlret = -1;
                    string biaoname = companyaccount + DAISHOUBIAONAME;

                    string cmd = string.Format("select * from {0} where Biao_Id IN ({1}) AND Biao_Status ='已到账';",
                        biaoname, inbiaoidsstr);
                    mainsql.opensql(SqlInfo1);
                    ds = mainsql.SqlExcuteWithReturn(cmd);
                    if (ds.Rows.Count.ToString() != biaocount.ToString())
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "系统表单获取错误，请刷新后尝试";
                        goto EXIT;
                    }
                    double allshishou = 0;//所有代收实收
                    foreach (DataRow drow in ds.Rows)//计算所有的代收实收
                    {
                        double dbttry = 0;
                        double.TryParse(drow["Biao_ShishouData"].ToString(), out dbttry);
                        allshishou += dbttry;
                    }
                    if (allshishou > comamount)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "该公司余额不足不支持立即提现功能";
                        goto EXIT;
                    }
                    daishousshouxu = allshishou * comfeilvdb;//获取代收手续费
                    daishousshouxu = Math.Round(daishousshouxu, 2);//将手续费变成两位小数
                    if (daishousshouxu < comminshouxudb)
                    {
                        daishousshouxu = comminshouxudb;
                    }
                    if (daishousshouxu >= allshishou)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "手续费不能大于或者等于代收款总额" + daishousshouxu.ToString() + "-" + allshishou.ToString(); ;
                        goto EXIT;
                    }
                    double allshifu = allshishou - daishousshouxu;
                    double realShouxu = daishousshouxu;
                    foreach (DataRow drow in ds.Rows)//计算所有的代收实收并且将其付款
                    {
                        #region 将每一单进行手续费计算并且付款操作
                        double shishou = 0;
                        if (double.TryParse(drow["Biao_ShishouData"].ToString(), out shishou) == false)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "票单的实收金额有误";
                            goto EXIT;
                        }
                        double nowshouxu = 0;
                        double nowshifu = 0;
                        if (shishou >= realShouxu)
                        {
                            nowshouxu = realShouxu;
                            nowshifu = shishou - realShouxu;
                            realShouxu = 0;
                        }
                        else
                        {
                            nowshouxu = shishou;
                            nowshifu = 0;
                            realShouxu = realShouxu - shishou;
                        }


                        intsertkeystr = " ";
                        intsertvaluestr = " ";

                        List<Dictionary<string, string>> ListMapArgs = new List<Dictionary<string, string>>();
                        CommonTools.LoadListMapByKeyStr(ref ListMapArgs, CommonTools.ALLDAISHOUZIDUAN);
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_Status", "'已付款'");
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_FukuanData", "'{realtime}'");
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_ShifuData", "'{shifu}'");
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_ShouxuData", "'{shouxu}'");
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_HuanpiaoData", "'未换票'");
                        CommonTools.ChangeListMapByKeyStr(ref ListMapArgs, "Biao_Default", "'小程序直接提现'");
                        logJieKou.Info(ListMapArgs.Count.ToString());
                        for (int i = 0; i < ListMapArgs.Count; i++)
                        {
                            intsertkeystr += string.Format(" {0} ", ListMapArgs[i]["Key"]);
                            if (i != ListMapArgs.Count - 1)
                            {
                                intsertkeystr += ",";
                            }

                            intsertvaluestr += string.Format(" {0} ", ListMapArgs[i]["Value"]);
                            if (i != ListMapArgs.Count - 1)
                            {
                                intsertvaluestr += ",";
                            }
                        }
                        intsertvaluestr = intsertvaluestr.Replace("{realtime}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        intsertvaluestr = intsertvaluestr.Replace("{shifu}", nowshifu.ToString());
                        intsertvaluestr = intsertvaluestr.Replace("{shouxu}", nowshouxu.ToString());

                        biaoname = companyaccount + DAISHOUBIAONAME;
                        string overbiaoname = companyaccount + OVERDAISHOUBIAONAME;

                        cmd = string.Format("insert into {0} ({1}) " +
                        "select {2} from " +
                        "{3} where Biao_Id = '{4}' ", overbiaoname, intsertkeystr,
                        intsertvaluestr, biaoname, drow["Biao_Id"].ToString());

                        sqlret = mainsql.SqlExcuteNoReturn(cmd);
                        if (sqlret != 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改运单状态失败";  //参数错误
                            goto EXIT;
                        }
                        cmd = string.Format("delete from {0} where Biao_Id = '{1}' ", biaoname, drow["Biao_Id"].ToString());
                        sqlret = mainsql.SqlExcuteNoReturn(cmd);
                        if (sqlret != 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "删除旧运单失败";  //参数错误
                            goto EXIT;
                        }
                        SaveGoodsStatus(mainsql, companyaccount + LISTBIAONAME, shop_name, "小程序用户",
                         drow["Biao_Id"].ToString(), "小程序代收提现", shop_name, "小程序平台", "托运人本人在小程序提取代收款");


                        #endregion
                    }
                    #region 插入付款记录表格

                    string FUNumber = CommonTools.Com_GetDaiShouNumber(mainsql, companyaccount, 3);

                    intsertkeystr = CommonTools.ALLDAISHOURECORDZIDUAN;
                    intsertvaluestr = CommonTools.ALLDAISHOURECORDZIDUAN;

                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Account", "'" + companyaccount + "'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Name", "'小程序'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Time", "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Count", "'" + FUNumber + "'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Dakuanrenphone", "''");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Dakuanren", "'小程序公司账户'");

                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Shoukuanrenphone", "'" + shop_name + "'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Shoukuanren", "'" + shop_name + "'");

                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Bankname", "'小程序账户'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Bankaccount", "'小程序账户'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Bank", "'小程序账户'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Allcost", "'" + allshifu.ToString() + "'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Allshouxucost", "'" + daishousshouxu.ToString() + "'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Ids", "'" + biaoids.Replace(',', ';') + "'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Type", "'付款'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Status", "'已付款'");
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Workerphone", "'" + shop_name + "'");//
                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Worker", "'" + shop_name + "'");

                    intsertvaluestr = intsertvaluestr.Replace("Contorl_Default", "'小程序直接提现'");
                    biaoname = companyaccount + DAKUANRECORDBIAONAME;
                    cmd = string.Format("insert into {0} ({1}) values ({2}) ",
                        biaoname, intsertkeystr, intsertvaluestr);
                    sqlret = mainsql.SqlExcuteNoReturn(cmd);
                    mainsql.closesql();
                    if (sqlret < 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "插入批次信息失败";  //参数错误
                        goto EXIT;
                    }

                    #endregion



                    using (TransactionScope tsall2 = new TransactionScope(TransactionScopeOption.RequiresNew))//进入事件
                    {
                        zfmainsql.openYongHuServicesql();
                        sqlcmd = string.Format("SELECT * from {0} where com_account='{1}'  ;", BIAOQGZHIFUCOMPANY, companyaccount);
                        ds = zfmainsql.SqlExcuteWithReturn(sqlcmd);
                        if (ds.Rows.Count == 0)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "公司相关信息错误";
                            goto EXIT;
                        }
                        comamount = 0;//公司余额
                        double.TryParse(ds.Rows[0]["com_amount"].ToString(), out comamount);
                        comamount = comamount - allshifu;

                        sqlcmd = string.Format("update {0} set com_amount='{1}'  where com_account='{2}' ",
                        BIAOQGZHIFUCOMPANY, comamount.ToString("0.00"), companyaccount);
                        sqlret = zfmainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改青贯账目失败";  //参数错误
                            goto EXIT;
                        }
                        sqlcmd = string.Format("update {0} set shop_balance=shop_balance+{1}  where shop_id='{2}' ",
                         S_SHOP, allshifu.ToString("0.00"), shop_id);
                        sqlret = zfmainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改商户账目失败";  //参数错误
                            goto EXIT;
                        }


                        sqlcmd = string.Format("update {0} set  order_pay_status='2', order_status='3'  where order_id='{1}' ",
                            S_ORDER, order_id);
                        sqlret = zfmainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改订单失败";  //参数错误
                            goto EXIT;
                        }

                        string defaultstr = string.Format("商户提现代收{0}元,扣除手续费提现{1}元", allshishou.ToString("0.00"), allshifu.ToString("0.00"));

                        sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_companyaccount," +
                         "zf_companynumber,zf_companyname,zf_companyamount," +
                         "zf_companyrealtimebalance,zf_default,zf_way,zf_shouzhi,zf_comshouzhi,zf_biaoid)" +
                         " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','零钱','0','2','{11}')",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "商户代收提现", "支付成功", qgliushuinumber,
                         companyaccount, companynumber, companyname, allshifu.ToString("0.00"), comamount.ToString("0.00"), defaultstr, biaoids);
                        sqlret = zfmainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "插入物流记录失败";  //参数错误
                            goto EXIT;
                        }
                        sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_companyaccount," +
                      "zf_companynumber,zf_companyname,zf_companyamount," +
                      "zf_companyrealtimebalance,zf_default,zf_way,zf_shouzhi,zf_comshouzhi,zf_biaoid)" +
                      " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','零钱','0','1','{11}')",
                     BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "商户代收提现", "支付成功", qgliushuinumber,
                      shop_id, "", shop_name, allshifu.ToString("0.00"),"",defaultstr, biaoids);
                        sqlret = zfmainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            zfmainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "插入商户记录失败";  //参数错误
                            goto EXIT;
                        }


                        zfmainsql.closesql();
                        tsall2.Complete();
                    }


                    mainsql.closesql();
                    tsall1.Complete();
                }



            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        */


        //获取账单列表
        //1正常账单
        //2零钱账单
        //3金币账单
        [WebMethod(Description = "正式版本")]
        public string xcx_getuserzhangdan(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();

            try
            {
                string phone = comrcv.Map_Args["phone"];
                string biaodate = comrcv.Map_Args["biaodate"];
                string pageindex = comrcv.Map_Args["pageindex"];
                string type = comrcv.Map_Args["type"];
                logJieKou.Info("小程序获取账单-" + phone);
                int pagecount = 100;
                int intpageindex = 0;
                int.TryParse(pageindex, out intpageindex);
                intpageindex = intpageindex * pagecount;
                string limitstring = string.Format("limit {0},{1} ", intpageindex, pagecount);
                mainsql.openYongHuServicesql();
                string sqlcmd = "";
                if (type == "1")//正常账单
                {
                    sqlcmd = string.Format("SELECT * FROM {0}" +
                    " where zf_status ='支付成功' AND zf_zfphone='{1}' AND zf_shouzhi <> '0' ORDER BY zf_time DESC {2} ;",
                    BIAOQGZHIFURECORD + biaodate, phone, limitstring);
                }
                else if (type == "2")//零钱账单
                {
                    sqlcmd = string.Format("SELECT * FROM {0}  " +
                   " where zf_status ='支付成功' AND zf_zfphone='{1}' AND zf_way='零钱' AND zf_shouzhi <> '0' ORDER BY zf_time DESC {2} ;",
                   BIAOQGZHIFURECORD + biaodate, phone, limitstring);
                }
                else if (type == "3")//金币账单
                {
                    sqlcmd = string.Format("SELECT * FROM {0}  " +
                    " where zf_status ='支付成功' AND zf_zfphone='{1}' AND zf_way='金币' AND zf_shouzhi <> '0' ORDER BY zf_time DESC {2} ;",
                    BIAOQGZHIFURECORD + biaodate, phone, limitstring);
                }

                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                if (ds.Rows.Count != 0)
                {
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }
                }
                mainsql.closesql();
            }
            catch (Exception ex)
            {
                logJieKou.Info("小程序获取账单-" + ex.Message);
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        //获取账单统计
        [WebMethod(Description = "正式版本")]
        public string xcx_getuserzhangdantj(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerZhiFu");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            try
            {
                string phone = comrcv.Map_Args["phone"];
                string biaodate = comrcv.Map_Args["biaodate"];

                logJieKou.Info("获取账单统计-" + phone);

                mainsql.openYongHuServicesql();
                string sqlcmd = string.Format("SELECT sum(zf_yhamount)" +
                    " FROM {0}  where zf_status ='支付成功' AND zf_zfphone='{1}' AND zf_shouzhi='1'  ;",
                    BIAOQGZHIFURECORD + biaodate, phone);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count != 0)
                {
                    ret.Map_Args.Add("shouru", ds.Rows[0]["sum(zf_yhamount)"].ToString());
                }
                sqlcmd = string.Format("SELECT sum(zf_yhamount)" +
                    " FROM {0}  where zf_status ='支付成功' AND zf_zfphone='{1}' AND zf_shouzhi='2'  ;",
                    BIAOQGZHIFURECORD + biaodate, phone);
                ds = mainsql.SqlExcuteWithReturn(sqlcmd);

                if (ds.Rows.Count != 0)
                {

                    ret.Map_Args.Add("zhichu", ds.Rows[0]["sum(zf_yhamount)"].ToString());
                }
                mainsql.closesql();
            }
            catch (Exception ex)
            {
                logJieKou.Info("聚合支付异常-" + ex.Message);
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                mainsql.closesql();
                goto EXIT;
            }
            ret.Byte_Flag = (sbyte)1;
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }

        public static string DAISHOUBIAONAME = "biaodaishouproperty";

        #endregion

    }
}